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.
原文地址:https://www.cnblogs.com/Answer1215/p/10222975.html
时间: 2024-10-16 05:42:52