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)
The
forEach
version of @travis-j's answer (helpful on modern browsers and Node JS world):34% faster on Chrome v29.0.1547: http://jsperf.com/filter-versus-dictionary/3
And a generic solution that takes a mapper function (tad slower than direct map, but that's expected):
underscore.js
_.uniq(_.pluck(array,"age"))
this function can unique array and object
use that like this
Here's a versatile solution that uses reduce, allows for mapping, and maintains insertion order.
items: An array
mapper: A unary function that maps the item to the criteria, or empty to map the item itself.
Usage
You can add this to your Array prototype and leave out the items parameter if that's your style...
You can also use a Set instead of an Array to speed up the matching.
Using ES6 features, you could do something like:
Using new Ecma features are great but not all users have those available yet.
Following code will attach a new function named distinct to the Global Array object. If you are trying get distinct values of an array of objects, you can pass the name of the value to get the distinct values of that type.
Check out my post in CodePen for a demo.