[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.

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10222975.html