set
let arr = [1,1,2,2,3,4,5,5,6,7,7,8,9,9];
let newArr = [...new Set(arr)];
console.log(newArr);//[1, 2, 3, 4, 5, 6, 7, 8, 9]
filter
// 这种方法会有一个问题:[1,'1']会被当做相同元素,最终输入[1]
function unique(arr) {
return arr.filter(function(item, index, arr) {
//当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
return arr.indexOf(item, 0) === index;
});
}
let arr = [1,1,2,2,3,4,5,5,6,7,7,8,9,9];
let newArr = unique(arr);
console.log(newArr);//[1, 2, 3, 4, 5, 6, 7, 8, 9]
reduce
let arr = [1,1,2,2,3,4,5,5,6,7,7,8,9,9];
let newArr = arr.reduce(function(ar,cur) {
if(!ar.includes(cur)) {
ar.push(cur)
}
return ar
},[]);
console.log(newArr);//[1, 2, 3, 4, 5, 6, 7, 8, 9]