Remove duplicates from an array of objects in JavaScript
How about with some es6
magic?
things.thing = things.thing.filter((thing, index, self) =>
index === self.findIndex((t) => (
t.place === thing.place && t.name === thing.name
))
)
Reference URL
A more generic solution would be:
const uniqueArray = things.thing.filter((thing, index) => {
const _thing = JSON.stringify(thing);
return index === things.thing.findIndex(obj => {
return JSON.stringify(obj) === _thing;
});
});
Stackblitz Example
Shortest one liners for ES6+
Find unique id
's in an array.
arr.filter((v,i,a)=>a.findIndex(t=>(t.id === v.id))===i)
Unique by multiple properties ( place
and name
)
arr.filter((v,i,a)=>a.findIndex(t=>(t.place === v.place && t.name===v.name))===i)
Unique by all properties (This will be slow for large arrays)
arr.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i)
Keep the last occurrence.
arr.slice().reverse().filter((v,i,a)=>a.findIndex(t=>(t.id === v.id))===i).reverse()
A primitive method would be:
var obj = {};
for ( var i=0, len=things.thing.length; i < len; i++ )
obj[things.thing[i]['place']] = things.thing[i];
things.thing = new Array();
for ( var key in obj )
things.thing.push(obj[key]);