snippetjavascriptCritical
How to get distinct values from an array of objects in JavaScript?
Viewed 0 times
arraydistincthowfromobjectsvaluesjavascriptget
Problem
Assuming I have the following:
What is the best way to be able to get an array of all of the distinct ages such that I get an result array of:
Is there some way I could alternatively structure the data or better method such that I would not have to iterate through each array checking the value of "age" and check against another array for its existence, and add it if not?
If there was some way I could just pull out the distinct ages without iterating...
Current inefficient way I would like to improve... If it means that instead of "array" being an array of objects, but a "map" of objects with some unique key (i.e. "1,2,3") that would be okay too. I'm just looking for the most performance efficient way.
The following is how I currently do it, but for me, iteration appears to just be crummy for efficiency even though it does work...
var array =
[
{"name":"Joe", "age":17},
{"name":"Bob", "age":17},
{"name":"Carl", "age": 35}
]What is the best way to be able to get an array of all of the distinct ages such that I get an result array of:
[17, 35]Is there some way I could alternatively structure the data or better method such that I would not have to iterate through each array checking the value of "age" and check against another array for its existence, and add it if not?
If there was some way I could just pull out the distinct ages without iterating...
Current inefficient way I would like to improve... If it means that instead of "array" being an array of objects, but a "map" of objects with some unique key (i.e. "1,2,3") that would be okay too. I'm just looking for the most performance efficient way.
The following is how I currently do it, but for me, iteration appears to just be crummy for efficiency even though it does work...
var distinct = []
for (var i = 0; i < array.length; i++)
if (array[i].age not in distinct)
distinct.push(array[i].age)Solution
If this were PHP I'd build an array with the keys and take
array_keys at the end, but JS has no such luxury. Instead, try this:var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
if( flags[array[i].age]) continue;
flags[array[i].age] = true;
output.push(array[i].age);
}Code Snippets
var flags = [], output = [], l = array.length, i;
for( i=0; i<l; i++) {
if( flags[array[i].age]) continue;
flags[array[i].age] = true;
output.push(array[i].age);
}Context
Stack Overflow Q#15125920, score: 157
Revisions (0)
No revisions yet.