1

I am working with Google Sheets and I would like to get a list with the unique items of another list. Namely the input is:

List = ['Nick','George','George','Nick','Nick','George','Nick','Alex']

The output will be :

[Nick, George, Alex]

Right now I am using a simple loop to check whether an element appears more than once. But I am sure there is going to be a more clever way.

soMarios
  • 24,472
  • 8
  • 28
  • 43
Stergios
  • 25
  • 5

2 Answers2

4

The simplest way is to use a Set. This is defined as a collection that cannot have duplicates

var noduplicates = new Set(List);

You can convert this back to a list if you wish.

var List = ['Nick', 'George', 'George', 'Nick', 'Nick', 'George', 'Nick', 'Alex']

var noduplicates = new Set(List)

noduplicates.forEach(x => console.log(x))
Jannes Carpentier
  • 1,788
  • 1
  • 3
  • 12
2

The answer is quite straightforward thanks to ES6. You need a combination of filter() and indexOf().

Here is the solution:

var List = ['Nick','George','George','Nick','Nick','George','Nick','Alex']
  
const unique = (value,index,self) =>
{return self.indexOf(value) ===index;}
var Unique_List=List.filter(unique); 

Unique_List will give you the desired result.

Output: [Nick, George, Alex]

References:

soMarios
  • 24,472
  • 8
  • 28
  • 43