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

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《两个数组去重合并(数组去重的5种方法)》的相关信息,《两个数组去重合并(数组去重的5种方法)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《两个数组去重合并(数组去重的5种方法)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

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]
笨笨网美国主机,w ww.2 b p .n e t
提醒:《两个数组去重合并(数组去重的5种方法)》最后刷新时间 2025-03-21 11:17:50,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《两个数组去重合并(数组去重的5种方法)》该内容的真实性请自行鉴别。