Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!