javaScript-----一维数组和数组对象去重的多种方法

在JavaScript中,可以使用多种方法对一维数组和数组对象进行去重。以下是一些常见的方法:

一维数组去重

1. 使用 Set

Set 只允许唯一值,可以直接用于一维数组的去重。

复制代码
const arr = [1, 2, 3, 1, 2];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3]
2. 使用 filterindexOf

通过 filter 方法配合 indexOf 来去重。

复制代码
const arr = [1, 2, 3, 1, 2];
const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index);
console.log(uniqueArr); // [1, 2, 3]
3. 使用 reduce

利用 reduce 方法进行去重。

复制代码
const arr = [1, 2, 3, 1, 2];
const uniqueArr = arr.reduce((acc, current) => {
    if (!acc.includes(current)) {
        acc.push(current);
    }
    return acc;
}, []);
console.log(uniqueArr); // [1, 2, 3]
4. 使用对象属性作为键

通过一个对象记录已存在的值,实现去重。

复制代码
const arr = [1, 2, 3, 1, 2];
const map = {};
const uniqueArr = arr.filter(item => {
    if (!map[item]) {
        map[item] = true;
        return true;
    }
    return false;
});
console.log(uniqueArr); // [1, 2, 3]

数组对象去重

1. 使用 SetJSON.stringify

利用 Set 的特性,结合 JSON.stringify 进行去重。

复制代码
const arr = [{ id: 1 }, { id: 2 }, { id: 1 }];
const uniqueArr = Array.from(new Set(arr.map(a => JSON.stringify(a)))).map(e => JSON.parse(e));
console.log(uniqueArr); // [{ id: 1 }, { id: 2 }]
2. 使用 filterfindIndex

通过 filter 方法配合 findIndex 来去重。

复制代码
const arr = [{ id: 1 }, { id: 2 }, { id: 1 }];
const uniqueArr = arr.filter((item, index) => 
    arr.findIndex(obj => JSON.stringify(obj) === JSON.stringify(item)) === index
);
console.log(uniqueArr); // [{ id: 1 }, { id: 2 }]
3. 使用 reduce

利用 reduce 方法进行去重。

复制代码
const arr = [{ id: 1 }, { id: 2 }, { id: 1 }];
const uniqueArr = arr.reduce((acc, current) => {
    const x = acc.find(item => JSON.stringify(item) === JSON.stringify(current));
    if (!x) {
        return acc.concat([current]);
    } else {
        return acc;
    }
}, []);
console.log(uniqueArr); // [{ id: 1 }, { id: 2 }]
相关推荐
北海-cherish2 小时前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
C嘎嘎嵌入式开发2 小时前
(2)100天python从入门到拿捏
开发语言·python
AALoveTouch3 小时前
网球馆自动预约系统的反调试
javascript·网络
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
2501_915909063 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
Vallelonga4 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧4 小时前
Rust模式匹配详解
开发语言·windows·rust
white-persist4 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
新中地GIS开发老师5 小时前
Cesium 军事标绘入门:用 Cesium-Plot-JS 快速实现标绘功能
前端·javascript·arcgis·cesium·gis开发·地理信息科学