两种简单的数组去重
1.利用splice直接改变原数组
/**题目 条件 [arr1,arr2] = [[1,1,1,2,2,3,4,5,5],[2,3,3,4,4,5,6,7,8,8,]]; 结果 arr = [1,2,3,4,5,6,7,8]; */ [arr1,arr2] = [[1,1,1,2,2,3,4,5,5],[2,3,3,4,4,5,6,7,8,8,]]; let arr = arr1.concat(arr2); arr.sort(); for(var i = 0; i < arr.length; i++){ if(arr[i] == arr[i + 1]){ arr.splice(i,1); i--; } } console.log(arr);
2.利用对象的属性名不会重复
[arr1,arr2] = [[1,1,1,2,2,3,4,5,5],[2,3,3,4,4,5,6,7,8,8,]]; var newArr = arr1.concat(arr2); var obj = {}; var arr =[]; for(var i = 0; i < newArr.length; i++) { if(!obj[newArr[i]]) { obj[newArr[i]] = '123'; //读取对象 和 写入对象 字符串的时候 都要用 [] arr.push(newArr[i]); } } console.log(arr);