1. 程式人生 > >[Tips + Javascript] Make a unique array

[Tips + Javascript] Make a unique array

function you 技術 hat short ray cti class only

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.

[Tips + Javascript] Make a unique array