Remove duplicate items from object array by key

To remove duplicate items from object array by key in Javascript, you just write a bit of code like this:

Write a function call removeDuplicates:

function removeDuplicates(myArr, prop) {
  return myArr.filter((obj, pos, arr) => {
    return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
  });
}


Usage:

const myArr = [
  { id: 1, name: "Jonh" },
  { id: 2, name: "Beth" },
  { id: 1, name: "Jonh" },
  { id: 3, name: "Hana" }
];
const myDate = removeDuplicates(myArr, "id");
// result: [{"id":1,"name":"Jonh"},{"id":2,"name":"Beth"},{"id":3,"name":"Hana"}] 


In this example, you can use another key like "name" to filter.

© 2019 4codev

Created with love by Sil.