Home >Web Front-end >JS Tutorial >How to Get Unique Values from an Array of Objects in JavaScript?

How to Get Unique Values from an Array of Objects in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-05 11:45:10342browse

How to Get Unique Values from an Array of Objects in JavaScript?

Retrieving Distinct Values from an Array of Objects in JavaScript

Your objective is to extract unique values of a particular property from an array of objects, specifically the "age" property. This task can be accomplished in multiple ways.

Using ES6 Set and Map Functions:

If your JavaScript version supports ES6, you can leverage the Set and Map data structures. The Set stores unique values, while the Map stores key-value pairs. Here's an efficient approach:

const uniqueAges = new Set(array.map(item => item.age));
console.log([...uniqueAges]); // [17, 35]

Traditional Looping and Checking:

If ES6 is not available, you can opt for a more traditional method using loops and checks:

const distinctAges = [];
for (const item of array) {
  if (!distinctAges.includes(item.age)) {
    distinctAges.push(item.age);
  }
}
console.log(distinctAges); // [17, 35]

Using an Object for Key-Value Storage:

Alternatively, if you can restructure your data, you could use an object to store unique values as keys, ensuring faster lookups.

const uniqueAgesObject = {};
for (const item of array) {
  uniqueAgesObject[item.age] = true;
}
const distinctAges = Object.keys(uniqueAgesObject);
console.log(distinctAges); // [17, 35]

By utilizing these techniques, you can effectively retrieve unique values from your array of objects, improving the efficiency of your code.

The above is the detailed content of How to Get 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