数组去重
第一种ES6写法
- new Set() Set结构不会添加重复的值
- 扩展运算符…转换成数组
var arr = [1,3,5,7,9,1,3,5]
let result = new Set(arr)
console.log([...result]); // [1,3,5,7,9]
第二种ES6写法
- new Set() Set结构不会添加重复的值
- Array.from()转换成数组
var arr = [1,3,5,7,9,1,3,5]
let result = new Set(arr)
console.log(Array.from(result)); // [1,3,5,7,9]
第三种sort+reduce
var arr = [1,2,1,2,3,5,4,5,3,4,4,4,4],
init=[]
var result = arr.sort().reduce((init, current)=>{
console.log(init,current)
if(init.length===0 || init[init.length-1]!==current){
init.push(current);
}
return init;
}, []);
console.log(result);//1,2,3,4,5
第四种使用indexOf和filter
var arr = [1, 2, 3, 1, 2, 3];
let result = arr.filter((item, index) => {
return arr.indexOf(item) === index
})
console.log(result) // [1,2,3]
第五种利用includes
let arr = [1, 2, 3, 1, 2, 3];
let result = []
arr.forEach((item,index) => {
if(!result.includes(arr[index])) {
result.push(item)
}
})
console.log(result); // [1,2,3]