I have an array of objects and I want to get a new array from it that is unique based only on a single property, is there a simple way to achieve this?
Eg.
[ { id: 1, name: 'bob' }, { id: 1, name: 'bill' }, { id: 1, name: 'bill' } ]
Would result in 2 objects with name = bill removed once.
I was looking for a solution which didn't require a library, and put this together, so I thought I'd add it here. It may not be ideal, or working in all situations, but it's doing what I require, so could potentially help someone else:
A better and quick approach
Found here
If you want to check all the properties then lodash 4 comes with _.uniqWith(sourceArray, _.isEqual)
You can use the _.uniqBy function
In the above example, filtering is based on the uniqueness of combination of properties id & name.
if you have multiple properties for an object. then to find unique array of objects based on specific properties, you could follow this method of combining properties inside _.uniqBy() method.
If you prefer to do things yourself without Lodash, and without getting verbose, try this uniq filter with optional uniq by property:
Then, use it like this:
Or for plain arrays, just omit the parameter, while remembering to invoke:
[1,1,2].filter(uniqFilterAccordingToProp())
In case you need pure JavaScript solution: