兩組數據合并去重 js兩個數組對象合并去重



文章插圖
兩組數據合并去重 js兩個數組對象合并去重

文章插圖
1、循環遍歷去重
定義一個空數組,循環原數組,檢測每一項是否在將新數組中,如果不在就將該項存儲到新數組中 。再循環新數組,將每一項還原為原來的類型,存入新的數組中,所得的新數組就是去重后得到數組 。
const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],res1 = [];arr.forEach((item) => {const str = JSON.stringify(item) + "";if (res1.indexOf(str) === -1) {res1.push(str);}});const res2 = res1.map((item) => {return item === undefined + "" ? undefined : JSON.parse(item);});console.log(res2); //[{a: 1, b: 1},true,0,1,null,undefined,false]2、利用對象的屬性名的不重復型
定義一個新的空對象,循環原數組,將每一項轉換為字符串的值作為對象的屬性名,每一項作為對象的屬性值 。然后遍歷對象,將對象屬性名對應的屬性值都放入一個新建的數組中 。所得的新數組就是去重后得到數組 。
const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],obj={};arr.forEach((item) => {const str = JSON.stringify(item) + "";obj[str]=item});const res = [];Object.keys(obj).forEach((item) => {res.push(obj[item]);});console.log(res); //[{a: 1, b: 1},true,0,1,null,undefined,false]3、利用ES6中Set的特性
循環數組,將數組中的每一項轉換為字符串,存入新的數組中 。利用Set集合元素的唯一性去重得到set集合,再將得到的set集合轉換為新的數組 。再循環新數組將每一項還原為原來的類型,存入新的數組中,所得的新數組就是去重后得到數組 。
【兩組數據合并去重 js兩個數組對象合并去重】const arr = [{ a: 1, b: 1 },true,0,1,null,undefined,true,false,1,{ a: 1, b: 1 },undefined,null,false,0],res1 = [];arr.forEach((item) => {const str = JSON.stringify(item) + "";res1.push(str);});const set = new Set(res1);const res2 = Array.from(set);const res3 = res2.map((item) => {return item === undefined + "" ? undefined : JSON.parse(item);});console.log(res3); //[{a: 1, b: 1},true,0,1,null,undefined,false]