Assuming I have the following:
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 inefficent 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. Im 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)
If like me you prefer a more "functional" without compromising speed, this example uses fast dictionary lookup wrapped inside reduce closure.
According to this test my solution is twice as fast as the proposed answer
my two cents on this function:
You can see the result here (Method 8) http://jsperf.com/distinct-values-from-array/3
Here's another way to solve this:
I have no idea how fast this solution is compared to the others, but I like the cleaner look. ;-)
EDIT: Okay, the above seems to be the slowest solution of all here.
I've created a performance test case here: http://jsperf.com/distinct-values-from-array
Instead of testing for the ages (Integers), I chose to compare the names (Strings).
Method 1 (TS's solution) is very fast. Interestingly enough, Method 7 outperforms all other solutions, here I just got rid of .indexOf() and used a "manual" implementation of it, avoiding looped function calling:
The difference in performance using Safari & Firefox is amazing, and it seems like Chrome does the best job on optimization.
I'm not exactly sure why the above snippets is so fast compared to the others, maybe someone wiser than me has an answer. ;-)
using d3.js v3:
using ES6
There are many valid answers already, but I wanted to add one that uses only the
reduce()
method because it is clean and simple.Use it like this: