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

How to Extract Unique Ages from an Array of Objects in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 01:56:12409browse

How to Extract Unique Ages from an Array of Objects in JavaScript?

Extracting Distinct Values from Array of Objects in JavaScript

Consider an array of objects where each object represents an individual with a name and age:

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

The task is to extract distinct ages from this array, resulting in a new array with unique values:

[17, 35]

JavaScript-Specific Solution (ES6 and above)

ES6 introduces the Set data structure, which automatically maintains a collection of unique values. This can be utilized to efficiently extract distinct ages:

const distinctAges = [...new Set(array.map(object => object.age))];

This approach creates a new array that includes only the unique values present in the age property of each object in the original array.

Alternative Data Structures

If performance is paramount, you may consider alternative data structures, such as a map or object:

const ageMap = {};
array.forEach(object => {
  ageMap[object.age] = true;
});

const distinctAges = Object.keys(ageMap).map(Number);

In this scenario, the age values are stored as keys in an object (map). The Object.keys() method retrieves the unique keys (age values) as an array, which is then converted to numeric values using map(Number).

Improved Method

The initial iteration method presented in the question can be improved by using the includes() method to check for duplicate values:

var distinct = [];
for (var i = 0; i < array.length; i++) {
  if (!distinct.includes(array[i].age)) {
    distinct.push(array[i].age);
  }
}

This optimization reduces the number of comparisons required by avoiding multiple checks for duplicate ages.

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