How to get distinct values from an array of objects in JavaScript?

How to get distinct values from an array of objects in JavaScript?

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)

Related:  TypeError: stepUp called on an object that does not implement interface HTMLInputElement


Solution 1:

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;

Solution 2:

If you are using ES6/ES2015 or later you can do it this way:

const unique = [ Set( => item.age))];

Here is an example on how to do it.

Solution 3:

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.

var unique = {};
var distinct = [];
for( var i in array ){
 if( typeof(unique[array[i].age]) == "undefined"){
 unique[array[i].age] = 0;

Here is a working demo:

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.

Related:  In ECMAScript5, what's the scope of “use strict”?

Performance When I ran this dictionary was 30% faster.

Solution 4:

using ES6

let array = [
  { "name": "Joe", "age": 17 },
  { "name": "Bob", "age": 17 },
  { "name": "Carl", "age": 35 }
]; => item.age)
  .filter((value, index, self) => self.indexOf(value) === index)

> [17, 35]

Solution 5:

this is how you would solve this using new Set via ES6 for Typescript as of August 25th, 2017

Array.from(new Set( any) =>

Solution 6:

Using ES6 features, you could do something like:

const uniqueAges = [ Set( => obj.age)) ];