Thursday, March 15, 2018

Get unique values from an array

var array = [1,2,3,4,1,2,1];
array.filter((x,i,a) => a.indexOf(x) == i);
// --result is as below
[1, 2, 3, 4];

filter method is explained as below
x--> the item in array
i--> the index of item
a--> the array itself

Looking for much shorter script? :-)
[... new Set(array)]
This gives the same result
[1, 2, 3, 4]

No comments:

Post a Comment