filter duplicate array object javascript code example
Example 1: how to remove duplicate array object in javascript
let person = [{name: "john"}, {name: "jane"}, {name: "imelda"}, {name: "john"}];
function removeDuplicates(data, key) {
return [
...new Map(data.map(item => [key(item), item])).values()
]
};
console.log(removeDuplicates(person, item => item.name));
Example 2: remove duplicate objects based on id from array angular 8
function getUnique(arr, comp) {
const unique = arr.map(e => e[comp])
.map((e, i, final) => final.indexOf(e) === i && i)
.filter((e) => arr[e]).map(e => arr[e]);
return unique;
}
console.log(getUnique(arr,'id'));
Example 3: remove duplicates objects from array javascript
arr.reduce((acc, current) => {
const x = acc.find(item => item.id === current.id);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
Example 4: remove duplicates objects from array javascript
function remove_duplicate_objects(data,prop) {
var seen = {};
data = data.filter(function (entry) {
if (seen.hasOwnProperty(entry[prop])) {
return false;
}
seen[entry.prop] = entry;
return true;
});
return data
}
const new_array = remove_duplicate_objects([array with objects inside])