How to create a list of unique items in JavaScript?

Viewed 62708

In my CouchDB reduce function I need to reduce a list of items to the unique ones.

Note: In that case it's ok to have a list, it will be a small number of items of string type.

My current way is to set keys of a object, then return the keys of that object since the place the code can't use things like _.uniq for example.

I'd like to find a more elegant way to spell it than this.

function(keys, values, rereduce) {
  // values is a Array of Arrays
  values = Array.concat.apply(null, values);
  var uniq = {};
  values.forEach(function(item) { uniq[item] = true; });
  return Object.keys(uniq);
}
9 Answers

The best method seem to be using ES6 and Set. Single line and faster* than above according to fiddle

    
const myList = [1,4,5,1,2,4,5,6,7];
const unique = [...new Set(myList)];
    
console.log(unique);

*tested in safari

This should work with anything, not just strings:

export const getUniqueList =  (a: Array<any>) : Array<any> => {

  const set = new Set<any>();

  for(let v of a){
      set.add(v);
  }

  return Array.from(set);

};

the above can just be reduced to:

export const getUniqueValues = (a: Array<any>) => {
   return Array.from(new Set(a));
};

:)

To get unique objects, you can use JSON.stringify and JSON.parse:

const arr = [{test: "a"}, {test: "a"}];
const unique = Array.from(new Set(arr.map(JSON.stringify))).map(JSON.parse);
console.log(unique);

I find the other answers to be rather complicated for no gain that I can see.

We can use the indexOf method of the Array to verify if an item exists in it before pushing:

const duplicated_values = ['one', 'one', 'one', 'one', 'two', 'three', 'three', 'four'];
const unique_list = [];

duplicated_values.forEach(value => {
  if (unique_list.indexOf(value) === -1) {
    unique_list.push(value);
  }
});

console.log(unique_list);

That will work with any type of variable as well, even objects (given the identifier actually reference the same entity, merely equivalent objects are not seen as the same).

Related