Home >Web Front-end >JS Tutorial >How Can I Efficiently Extract Unique Values from an Array of Objects in JavaScript?

How Can I Efficiently Extract Unique Values from an Array of Objects in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 16:40:12233browse

How Can I Efficiently Extract Unique Values from an Array of Objects in JavaScript?

Efficiently Extracting Distinct Values from an Array of Objects in JavaScript

In JavaScript, obtaining distinct values from an array of objects can be a common task. Consider the following scenario:

var array = [
  { name: "Joe", age: 17 },
  { name: "Bob", age: 17 },
  { name: "Carl", age: 35 }
];

// Desired Result: [17, 35]

To achieve this result, one approach is to iterate through the array and maintain a separate array to store distinct values. However, this method can be inefficient, especially for large arrays.

An alternative approach, available in ES6/ES2015 and later, utilizes the Set data structure. Sets provide a unique collection of values, so you can create a new Set from the array of objects' desired property:

const uniqueAges = [...new Set(array.map(item => item.age))];

This statement iterates through the array using the map() function to extract the age property from each object. It then creates a Set from the extracted values using the new Set() constructor. Finally, it spreads the Set into an array using the spread operator (...), resulting in the desired list of distinct ages: [17, 35].

This approach offers significant performance benefits compared to the iterative method, especially for large datasets. It eliminates the need for additional data structures and minimizes the number of iterations required.

The above is the detailed content of How Can I Efficiently Extract Unique Values from an Array of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn