Given an array of objects, the task is to extract a new array containing only the distinct values of a specific property. For instance, consider the following array:
var array = [ { "name": "Joe", "age": 17 }, { "name": "Bob", "age": 17 }, { "name": "Carl", "age": 35 } ]
The objective is to obtain an array containing the distinct ages from this array, resulting in:
[17, 35]
Iterative Solution
A straightforward approach involves iterating through the objects in the array and checking if each object's age exists in the result array. If not, the age is added to the result array. This approach, although functional, is inefficient due to its reliance on multiple iterations and comparisons.
var distinct = [] for (var i = 0; i < array.length; i++) if (array[i].age not in distinct) distinct.push(array[i].age)
Optimized Solution Using ES6 Set
For more efficient handling, ES6/ES2015 offers the Set data structure, which enables the storage of unique values. Here's how to utilize it:
const data = [ { "group": 'A', "name": 'SD' }, { "group": 'B', "name": 'FI' }, { "group": 'A', "name": 'MM' }, { "group": 'B', "name": 'CO'} ]; const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']
By mapping the array of objects to an array of their desired property values and creating a Set from it, we eliminate duplicate values. Then, converting the Set back to an array using the spread operator (...) produces the desired result.
The above is the detailed content of How to Efficiently Extract Unique Property Values from an Array of JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!