JS常见的几种数组去重方法:
- indexOf
includes
-
filter+indexOf
-
双重
for
循环 -
Set
-
reduce
1.indexOf
<script>
// 数组去重
let arr1 = [1,1,2,3,4,55,4,4]
let arr2 = []
arr2.push(arr1[0])
for(let i = 1; i < arr1.length; i++){
if(arr2.indexOf(arr1[i]) === -1){
arr2.push(arr1[i])
}
}
console.log(arr2); //[1,2,3,4,55]
</script>
2.includes
与indexof
一个道理,indexof 找不到返回 -1 ,includes 找不到返回 false
// 数组去重
let arr1 = [1, 1, 2, 3, 4, 55, 4, 4]
let arr2 = []
arr2.push(arr1[0])
for (let i = 1; i < arr1.length; i++) {
if (arr2.includes(arr1[i]) === false) {
arr2.push(arr1[i])
}
}
console.log(arr2);
3.filter+indexOf
var arr = [2,36,12,2,5,36,36,12,26,65,65]
arr = arr.filter((item,index,arr)=>{
// index为数组中值得索引 2->0 36->1 12->2 2->3 5->4 ...
// arr.indexOf(item,0) 为返回第一次找的值的索引 2->0 36->1 12->2 2->0 5->4 ....
// 如果两次的索引值相等 就返回 (过滤了索引相同的值)
// indexOf 返回第一次找的值的索引
return arr.indexOf(item,0) === index
})
console.log(arr); //[2,36,12,5,26,65]
4.双重for
循环
var arr = [2,36,12,2,5,36,36,12,26,65,65]
for(var i = 0,len = arr.length; i < len; i++){
for (var j = i+1, len = arr.length; j < len; j++) {
if(arr[i] === arr[j]){
arr.splice(i,1)
j-- //每减一个 就少一个
len--
}
}
}
console.log(arr);
5.Set(es6)
var arr = [2,36,12,2,5,36,36,12,26,65,65]
// var newArr = new Set(arr)
var newArr = new Set()
for(var i in arr){
newArr.add(arr[i])
}
console.log(newArr); //set的数据结构
console.log(Array.from(newArr)); //转化为数组
console.log([...newArr]); //转化为数组
6.reduce
let arr = [1,2,1,3,6,9,6,9,6,6]
var newArr = arr.reduce((pre,cur)=>{
if(!pre.includes(cur)){
pre.push(cur)
}
return pre
}, [])
console.log(newArr); //[1, 2, 3, 6, 9]