好猫网手机站
两个数组去重合并(数组去重的5种方法)
2022-08-15 18:29:23  浏览:28

两个数组去重合并(数组去重的5种方法)

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集合转换为新的数组。再循环新数组将每一项还原为原来的类型,存入新的数组中,所得的新数组就是去重后得到数组。

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]