Home >Web Front-end >JS Tutorial >How to Extract Unique Ages from an 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]
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.
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).
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!