I have an object that contains an array of objects.
obj = {}; obj.arr = new Array(); obj.arr.push({place:"here",name:"stuff"}); obj.arr.push({place:"there",name:"morestuff"}); obj.arr.push({place:"there",name:"morestuff"});
I'm wondering what is the best method to remove duplicate objects from an array. So for example, obj.arr
would become...
{place:"here",name:"stuff"}, {place:"there",name:"morestuff"}
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
How about with some es6
magic?
obj.arr = obj.arr.filter((value, index, self) => index === self.findIndex((t) => ( t.place === value.place && t.name === value.name )) )
Reference URL
A more generic solution would be:
const uniqueArray = obj.arr.filter((value, index) => { const _value = JSON.stringify(value); return index === obj.arr.findIndex(obj => { return JSON.stringify(obj) === _value; }); });
Using the above property strategy instead of JSON.stringify
:
const isPropValuesEqual = (subject, target, propNames) => propNames.every(propName => subject[propName] === target[propName]); const getUniqueItemsByProperties = (items, propNames) => items.filter((item, index, array) => index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames)) );
You can add a wrapper if you want the propNames
property to be either an array or a value:
const getUniqueItemsByProperties = (items, propNames) => { const propNamesArray = Array.from(propNames); return items.filter((item, index, array) => index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray)) ); };
allowing both getUniqueItemsByProperties('a')
and getUniqueItemsByProperties(['a']);
Stackblitz Example
Explanation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With