How to Get Distinct Values from an Array of Objects in Javascript?

When working with arrays of objects in JavaScript, you may often come across the need to retrieve distinct values from the array. In other words, you want to remove any duplicate objects and only keep one instance of each unique object. In this blog post, we will explore different approaches to achieve this in JavaScript.

1. Using Set

One of the easiest ways to get distinct values from an array of objects is by utilizing the Set data structure introduced in ES6. The Set object allows you to store unique values of any type, including objects.

Here’s how you can use Set to get distinct values from an array of objects:

const array = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Bob' },
  { id: 2, name: 'Jane' }
];

const distinctArray = Array.from(new Set(array.map(JSON.stringify))).map(JSON.parse);

console.log(distinctArray);

Output:

[
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
]

In the code snippet above, we first use the map method to convert each object in the array to its string representation using JSON.stringify. Then, we create a Set from the resulting array of strings. Since Set only allows unique values, any duplicate strings (representing duplicate objects) will be automatically removed. Finally, we convert the Set back to an array of objects using Array.from and map with JSON.parse.

2. Using reduce

Another approach to get distinct values from an array of objects is by using the reduce method. This method allows you to iterate over the array and accumulate a new array of distinct objects.

Here’s an example of how you can achieve this:

const array = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 1, name: 'John' },
  { id: 3, name: 'Bob' },
  { id: 2, name: 'Jane' }
];

const distinctArray = array.reduce((accumulator, current) => {
  const existingObject = accumulator.find(obj => obj.id === current.id);
  if (!existingObject) {
    accumulator.push(current);
  }
  return accumulator;
}, []);

console.log(distinctArray);

Output:

[
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Bob' }
]

In the code snippet above, we use the reduce method to iterate over the array and accumulate a new array of distinct objects. For each object in the array, we check if there is already an object with the same id in the accumulator array using the find method. If not, we push the current object into the accumulator array. Finally, we return the accumulator array.

These are two common approaches to get distinct values from an array of objects in JavaScript. Depending on your specific use case, one approach may be more suitable than the other. Feel free to experiment with both and choose the one that best fits your needs.


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *