user
How to get distinct values from an array of objects in JavaScript?
alphonsio

To get distinct values from an array of objects in JavaScript, you can use a combination of methods like map(), Set, and filter(). Here's a general approach:

  1. First, use the map() method to iterate over the array and return a new array that contains the values you're interested in.

  2. Then, use the Set object to remove duplicates from this new array. Set is a built-in JavaScript object that lets you store unique values of any type.

  3. Finally, if you need to convert the Set back to an array, you can use the spread operator (...).

Here's an example where we're getting distinct values of a property called id from an array of objects:

let array = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Mary' },
  { id: 1, name: 'Bob' },
  { id: 3, name: 'Alice' },
  { id: 2, name: 'Sara' }
];

let distinctIds = [...new Set(array.map(item => item.id))];

console.log(distinctIds);  // Output: [1, 2, 3]

In this example, array.map(item => item.id) returns a new array [1, 2, 1, 3, 2]. new Set(...) removes the duplicates and returns a Set object {1, 2, 3}. The spread operator ... converts the Set back to an array [1, 2, 3].


If you want to get distinct objects based on all properties, not just one, you can use a combination of map(), JSON.stringify(), Set, JSON.parse(), and filter():

let array = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Mary' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Alice' },
  { id: 2, name: 'Mary' }
];

let distinctObjects = array
  .map(JSON.stringify)
  .filter((item, index, self) => self.indexOf(item) === index)
  .map(JSON.parse);

console.log(distinctObjects);
// Output: [ { id: 1, name: 'John' }, { id: 2, name: 'Mary' }, { id: 3, name: 'Alice' } ]

In this example, array.map(JSON.stringify) converts each object to a JSON string. filter((item, index, self) => self.indexOf(item) === index) removes the duplicate JSON strings. map(JSON.parse) converts the JSON strings back to objects.