JS数组去重整理合集
1.利用splice
1 var arr = [1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1]; 2 3 function repeat(arr){ 4 for(var i = 0;i<arr.length;i++){ 5 for(var j = i+1;j<arr.length;j++){ 6 if(arr[i] == arr[j]){ 7 arr.splice(j,1); 8 j--; 9 } 10 } 11 } 12 return arr 13 } 14 console.log(repeat(arr)); 15 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
2.利用reduce
1 var arr = [1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1] 2 var newArr = arr.reduce((prev, cur) => { 3 prev.indexOf(cur) === -1 && prev.push(cur); 4 return prev; 5 }, []); 6 console.log(newArr); 7 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
3.利用Set
1 function repeat(newarr){ 2 var s = new Set(arr); 3 var a = []; 4 for(var i of s){ 5 a.push(i) 6 } 7 return a; 8 } 9 var a = repeat(arr) 10 console.log(a) 11 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
12 console.log([...new Set([1, 2, 3, 1])]);
4.利用indexOf
1 function repeat(newarr){ 2 var array = []; 3 for(var i=0;i < newarr.length;i++){ 4 if(array.indexOf(newarr[i]) === -1){ 5 array.push(newarr[i]) 6 } 7 } 8 return array; 9 } 10 console.log(repeat(arr)) 11 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
5.利用includes
1 function repeat(newarr) { 2 var array =[]; 3 for(var i = 0; i < newarr.length; i++) { 4 if( !array.includes( newarr[i]) ) { 5 array.push(newarr[i]); 6 } 7 } 8 return array; 9 } 10 console.log(repeat(arr)); 11 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
6.利用filter
1 function repeat(newarr) { 2 return newarr.filter((item, index, arr)=> { 3 return newarr.indexOf(item, 0) === index; 4 }); 5 } 6 console.log(repeat(arr)); 7 //[1, 2, 3, 4, 5, 6, 7, 8, 9]
7.利用封装函数(逻辑简单)
1 function has(arr, n) { 2 for (var i = 0; i < arr.length; i++) { 3 if (arr[i] == n) { 4 return true; //如果在里面则返回true; 5 } 6 } 7 return false; //否则返回false; 8 } 9 10 function norepeat(myArr) { 11 var newArr = []; //定义一个空数组,存放符合条件的值; 12 for (var j = 0; j < myArr.length; j++) { 13 if (!has(newArr, myArr[j])) { //利用封装好的函数has判断空数组中是否存在当前的值; 14 newArr.push(myArr[j]); //如果空数组中没有,那么则push进空数组; 15 } 16 } 17 return newArr; 18 } 19 console.log(norepeat(arr)) 20 //[1, 2, 3, 4, 5, 6, 7, 8, 9]