[Tips + Javascript] Make a unique array

To make an array uniqued, we can use Set() from Javascript.

const ary = ["a", "b", "c", "a", "d", "c"];
console.log(new Set(ary));

We can see that all the duplicated value have been removed,  now the only thing we need to do is convert Set to Array.

 

So we have Array.from:

const ary = ["a", "b", "c", "a", "d", "c"];
const res = uniqueArray(ary);
console.log(res);

function uniqueArray(ary) {
  return Array.from(new Set(ary));
}

 

Or even shorter:

const ary = ["a", "b", "c", "a", "d", "c"];
const res = uniqueArray(ary);
console.log(res);

function uniqueArray(ary) {
  return [...new Set(ary)];
}

 Whichever you prefer.

 

 

posted @ 2019-01-04 23:11  Zhentiw  阅读(153)  评论(0)    收藏  举报