js 实现json数组集合去重,差集,并集,交集。
let list = [ { id: "1", content: "A" }, { id: "2", content: "B" }, { id: "3", content: "C" }, { id: "4", content: "D" } ]; let arr = [ { id: "1", content: "C" }, { id: "2", content: "D" } ]; // let list = [1, 2, 3, 4, 5]; // let arr = [3, 4]; // 去重 function listRemoveRepeat(x) { let result = []; for (let i = 0; i < x.length; i++) { let flag = true; let temp = x[i]; for (let j = 0; j < result.length; j++) { // 普通数组 (temp === result[j]) if (temp.id === result[j].id) { flag = false; break; } } if (flag) { result.push(temp); } } return result; } // 差集 function listDifference(x, y) { let clone = x.slice(0); for (let i = 0; i < y.length; i++) { let temp = y[i]; for (let j = 0; j < clone.length; j++) { // 普通数组 (temp === clone[j]) if (temp.id === clone[j].id) { clone.splice(j, 1); } } } return listRemoveRepeat(clone); } // 并集 function listConcat(x, y) { return listRemoveRepeat(x.concat(y)); } // 交集 function listIntersection(x, y) { let result = []; for (let i = 0; i < y.length; i++) { let temp = y[i]; for (let j = 0; j < x.length; j++) { // 普通数组 (temp === clone[j]) if (temp.id === x[j].id) { result.push(temp); break; } } } return listRemoveRepeat(result); } console.log("去重", listRemoveRepeat(list)); console.log("差集", listDifference(list, arr)); console.log("并集", listConcat(list, arr)); console.log("交集", listIntersection(list, arr));
学习在于积累:滴水可以石穿! 学而不思则罔,思而不学则殆!