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.

Marios
  • 26,333
  • 8
  • 32
  • 52
Stergios
  • 25
  • 1
  • 5

2 Answers2

5

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,838
  • 1
  • 5
  • 12
3

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:

Marios
  • 26,333
  • 8
  • 32
  • 52