网站首页 > 基础教程 正文
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]
猜你喜欢
- 2024-11-13 第19节 Array数组-Web前端开发之Javascript-零点程序员
- 2024-11-13 找出JavaScript中两个数组之间的差异
- 2024-11-13 获取javascript数组所有重复元素的索引的函数,js实战经验
- 2024-11-13 JavaScript遍历对象及数组方法小结
- 2024-11-13 web开发之-js数组常用方法(1) js数组常用操作
- 2024-11-13 Javascript中判断数组的正确姿势 js如何判断一个数组
- 2024-11-13 JavaScript中的数组Array(对象) js数组entries
- 2024-11-13 JavaScript判断一个变量是否是数组的6个方法
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)