const arr = [1, 5, '5', 'a','c','a' true, true, false, false, 'true', 'a', {}, {}];
思路:
- 使用set,然后转数组
- 循环,通过数组类似包含的方法判断
- 通过Map, 空间换时间
1. Array.from & Set
The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object
Array.from(new Set(arr))
2.indexof,includes,filter
const unique = arr => {
const res = [];
for (let i = 0,len = arr.length; i < len; i++) {
if (res.indexOf(arr[i]) === -1) {
res.push(arr[i]);
}
}
return res;
}
3. map
const unique = arr => {
const map = new Map();
const res = [];
for (let i = 0,len = arr.length ; i < len; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], true)
res.push(arr[i]);
}
}
return res;
}