js数组去重,除重的方式(尽可能多)

    科技2024-12-26  7

    测试数组:

    let arr = [3, 1, 0, 0, 1, 1, 2, 3, 4, 2, 1, 2, 4, 2, 3, 0, 2, 4, 2, 1, 4, 5, 5, 5, 3];

    先来几个简单的

    //数组去重-1 function arrayUniq_1(arr){ let o = {}; for (let i = 0; i<arr.length; i++){ var t = arr[i] if(typeof o[t] !== "undefined"){ arr[i] = arr[arr.length-1] arr.length--; i--;; } o[t] = t; } o = null; return arr; } console.log("数组除重-1:" + arrayUniq_1(arr)); //数组去重0 function arrayUniq0(arr) { let result = [...new Set(arr)] return result; } console.log("数组除重0:" + arrayUniq0(arr)); //数组去重1 function arrayUniq1(arr) { let result = arr.filter((item, index, array) => { return array.lastIndexOf(item) == index }) return result; } console.log("数组除重1:" + arrayUniq1(arr)); //数组去重2 function arrayUniq2(arr) { let result = []; arr.forEach(element => { result.indexOf(element) == -1 && result.push(element) }); return result; } console.log("数组除重2:" + arrayUniq2(arr)); //数组去重3 function arrayUniq3(arr) { let obj = {}; var resultArr = []; for (let index = 0; index < arr.length; index++) { if (!(arr[index] in obj)) { obj[arr[index]] = 0; resultArr.push(arr[index]); } } return resultArr; } console.log("数组除重3:" + arrayUniq3(arr));

    双层循环不能少

    //数组去重4 function arrayUniq4(arr) { var resultArr = []; for (let index = 0; index < arr.length; index++) { let j = 0; for (let i = 0; i < arr.length; i++) { if (arr[index] == arr[i]) { j++; if (j > 1) { delete arr[i]; } } } if (arr[index] != undefined) { resultArr.push(arr[index]); } } return resultArr; } console.log("数组除重4:" + arrayUniq3(arr)); // for forEach for...in.. 两两组合 没意思不写了 // for forEach for...in.. 替换除重1的外部循环 // for forEach for...in.. 替换除重2的外部循环

    替换一下1方法

    //数组去重5 function arrayUniq5(arr) { let result = [].filter.call(arr, (item, index, array) => { return array.lastIndexOf(item) == index }) return result; } console.log("数组除重5:" + arrayUniq5(arr)); //数组去重8 function arrayUniq8(arr) { let result = [].filter.bind(arr)((item, index, array) => { return array.lastIndexOf(item) == index }) return result; } console.log("数组除重8:" + arrayUniq8(arr)); //数组去重9 function arrayUniq9(arr) { let result = [].filter.apply(arr, [(item, index, array) => { return array.lastIndexOf(item) == index }]) return result; } console.log("数组除重9:" + arrayUniq9(arr)); // 按照 5,8,9 进行替换 你懂得有多少种

    替换下外部

    //数组去重6 function arrayUniq6(arr) { let obj = {}; var resultArr = []; [].forEach.call(arr, element => { if (!(element in obj)) { obj[element] = 0; resultArr.push(element); } }) return resultArr; } console.log("数组除重6:" + arrayUniq6(arr)); //数组去重7 function arrayUniq7(arr) { let obj = {}; var resultArr = []; [].forEach.bind(arr, element => { if (!(element in obj)) { obj[element] = 0; resultArr.push(element); } })() return resultArr; } console.log("数组除重7:" + arrayUniq7(arr));

    由此推算 … 你懂得(滑稽练)

    Processed: 0.076, SQL: 8