Unique From an Array of Objects in Javascript

Ran into this great github thread.

Normally, you would extract unique values with Set and spread.

array = [1, 2, 3, 1, 2, 3]
unique = [ ...new Set(array) ] 
//[1, 2, 3]

But with array of objects, it get’s a little more complicated.

uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s))

Or with Lodash

const _ = require('lodash');
...
_.uniq([1,2,3,3,'a','a','x'])//1,2,3,'a','x'
_.uniqBy([{a:1,b:2},{a:1,b:2},{a:1,b:3}], v=>v.a.toString()+v.b.toString())//[{a:1,b:2},{a:1,b:3}]

Leave a Comment