-1

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);
  • concat and do this https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects – cmgchess Jul 18 '22 at 18:52

2 Answers2

3

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);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
1

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);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51