js数组去重
1、定义一个新数组,并存放原数组的第一个元素,然后将元素组一一和新数组的元素对比,若不同则存放在新数组中。
var arr = [1,2,3,1,2,5,4,5,2,1,2,3,1,2,1]; var arrr = [1]; for(var i=0;i<arr.length;i++){ var flag = false; for(var j=0;j<arrr.length;j++){ if (arr[i] == arrr[j]) { flag = true; break; } } if (!flag) { arrr.push(arr[i]); }
} console.log(arrr)
2、先将原数组排序,在与相邻的进行比较,如果不同则存入新数组
// 将原数组排序组成新的数组 var arr = [1,2,3,1,2,5,4,5,2,1,2,3,1,2,1]; var arr2 = arr.sort(); var res = [arr2[0]]; for(var i=0;i<arr2.length;i++){ if (arr2[i] !== res[res.length-1]) { res.push(arr2[i]); } } console.log(res);
3、利用对象的属性去重(推荐)
var arr = [1,2,3,1,2,5,4,5,2,1,2,3,1,2,1]; var res = []; var json = {}; for(var i=0;i<arr.length;i++){ if (!json[arr[i]]) { res.push(arr[i]); json[arr[i]] = 1; } } console.log(res);
4、利用下标查询
var arr = [1,2,3,1,2,5,4,5,2,1,2,3,1,2,1]; var newArr = [arr[0]]; for(var i=1;i<arr.length;i++){ if (newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]); } } console.log(newArr)
5、利用ES6方法 - set去重
var arr = [1,2,3,1,2,5,4,5,2,1,2,3,1,2,1]; function fn(arr){ var s = new Set(arr); return Array.from(s); } console.log(fn(arr))
6、数组对象去重
function unique(arr) { const res = new Map(); return arr.filter((arr) => !res.has(arr.orderNumber) && res.set(arr.orderNumber, 1)) } let arr = [ {"tid": "1476441758236913665", "state": 1, "orderNumber": "HK-2020050065"}, {"tid": "1476442625975496706", "state": 1, "orderNumber": "HK-2020060223"}, {"tid": "1476442749619384321", "state": 1, "orderNumber": "HK-2020060223"}, {"tid": "1476443010194714625", "state": 1, "orderNumber": "HK-2020060221"}, {"tid": "1476444086746722306", "state": 1, "orderNumber": "HK-2020060221"}, {"tid": "1476444379194568706", "state": 1, "orderNumber": "HK-2020060221"} ] let newArr = unique(arr) //调用方法 console.log(newArr)