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

92
Vistas
ES6 map.has is not a function when called in a reducer

I want to return an array of objects without any duplicate ids. If there are any, then take the first one we see. So, we should NOT see {id: "2", value: '10'}. Instead, the value should be "Italian". I have this code below, but I am getting an map.has is not a function error.

const arr1 = [{
    id: "1",
    value: "English"
  },
  {
    id: "2",
    value: "Italian"
  }
];

const arr2 = [{
    id: "2",
    value: '10'
  },
  {
    id: "3",
    value: "German"
  }
];

const concatArr = arr1.concat(arr2);
const mergedArr = [...concatArr.reduce((map, obj) => map.has(obj.id) ? "" : map.set(obj.id, obj), new Map()).values()];

console.log(mergedArr);
about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

You need to always return a map not an empty string when the thing is already in the map.

const arr1 = [{
    id: "1",
    value: "English"
  },
  {
    id: "2",
    value: "Italian"
  }
];

const arr2 = [{
    id: "2",
    value: '10'
  },
  {
    id: "3",
    value: "German"
  }
];

const concatArr = arr1.concat(arr2);
const mergedArr = [...concatArr.reduce((map, obj) => map.has(obj.id) ? map : map.set(obj.id, obj), new Map()).values()];

console.log(mergedArr);

about 4 years ago · Santiago Gelvez Denunciar

0

You can use array#reduce to uniquely identify each object with unique id in an object accumulator and then extract all values from this object using Object.values().

const arr1 = [{ id: "1", value: "English" }, { id: "2", value: "Italian" } ],
      arr2 = [{ id: "2", value: '10' }, { id: "3", value: "German" } ],
      result = Object.values(arr1.concat(arr2).reduce((r, o) => {
        r[o.id] = r[o.id] || o;
        return r;
      },{}));
console.log(result);

about 4 years ago · Santiago Gelvez 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