Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda