Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
I am trying to make my own Set() method in JavaScript. But getting unexpected output

I'm kind of wanted to create my own set() method as mySet() for unique element from an array. But getting wrong output. help me out.

let arr = [1,2,3,4,5,2,8,1,3,1]
function mySet(arr){
    let mapObj = {}
    let newArr = []
    for (let i = 0; i <arr.length; i++) {
        if(mapObj[arr[i]]){
           //skip
        }else{
            mapObj[arr[i]]=i
            newArr.push(arr[i])
        }
    }
    return newArr;
}
console.log(mySet(arr)) //i wanted [1,2,3,4,5,8] getting  [1,2,3,4,5,8,1] 
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need a truthy value for the object in this case, you can use true.

The check returns with zero (the first index) the same result as if you have not assigned any value to the property.

function mySet(arr) {
  let mapObj = {}
  let newArr = []
  for (let i = 0; i < arr.length; i++) {
    if (!mapObj[arr[i]]) {
      mapObj[arr[i]] = true;
      newArr.push(arr[i])
    }
  }
  return newArr;
}

let arr = [1, 2, 3, 4, 5, 2, 8, 1, 3, 1]

console.log(mySet(arr));

about 4 years ago · Juan Pablo Isaza Denunciar

0

mapObj[arr[i]]=i assigns the current index.

if(mapObj[arr[i]]){ treats the value as a boolean.

The first index of the value 1 occurs at 0.

So you say mapObj[1] = 0 which is false.

You need to assign true instead of i.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda