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)
using lodash
I've started sticking Underscore in all new projects by default just so I never have to think about these little data-munging problems.
Produces
[17, 35]
.this is how you would solve this using new Set via ES6 for Typescript as of August 25th, 2017
You could use a dictionary approach like this one. Basically you assign the value you want to be distinct as the key in a dictionary. If the key did not exist then you add that value as distinct.
Here is a working demo: http://jsfiddle.net/jbUKP/1
This will be O(n) where n is the number of objects in array and m is the number of unique values. There is no faster way than O(n) because you must inspect each value at least once.
Performance
http://jsperf.com/filter-versus-dictionary When I ran this dictionary was 30% faster.