1、纯数组(不含对象或子数组)
var array = [1,2,3,3,4,5]; console.log(Array.from(new Set(array))) //输出 [1, 2, 3, 4, 5]
2、含对象或子数组的
function ret(arr) { const res = []; const json = {}; for (let i = 0; i < arr.length; i++) { if (!json[arr[i].id]) { res.push(arr[i]); json[arr[i].id] = arr[i].id; } } return res; } const arr = [ { id: 1, name: "张三" }, { id: 1, name: "张三" } ]; ret(arr);
3、去重并且合并对象
function ret(arr) { const res = []; const json = {}; for (let i = 0; i < arr.length; i++) { var ai = arr[i]; if (!json[ai.id]) { res.push(ai); json[ai.id] = ai.id; }else{ for (var j = 0; j < res.length; j++) { var dj = res[j]; if (dj.id=== ai.id) { dj.val = dj.val.concat(ai.val); // 也可以写其它合并代码 break; } } } return res; } const arr = [ { id: 1, name: "张三", val: [ a: 1 ] }, { id: 1, name: "张三", val: [ b: 2 ] } ]; ret(arr);