Friday, March 28, 2025

Distinct Array Values in JavaScript

Sometimes when you're working with collections (in any language) you find yourself needing to get just the distinct list of items in the collection. JavaScript has an object called a Set that makes doing this with arrays really, really easy.

Start with an array of primitives:

let arr = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1, 1, 1, 1, 3, 4, 5, 6]

From that array, create a Set: 

let set = new Set(arr)

Convert it back to an array (this step is optional because you may find working with the Set directly meets your needs):

let result = Array.from(set);

That's it. Now you have an array of distinct primitive values. If you have an array of complex objects, you can use this same trick, but it's a little... trickier.

let arr = [{id:1,name:'Frodo',relatives:[{id:2,name:'Bilbo'}]},{id:1,name:'Frodo',relatives:[{id:2,name:'Bilbo'}]}];
let set = new Set(arr.map(JSON.stringify));
let result = Array.from(set);

No comments:

Post a Comment