For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /note/js/array-unique.md.

数组去重

需求:

多组数组元素组合拼接,最终导致数组中有一些重复出现的元素。现将数组中重复的元素剔除掉,最终得到一组没有重复数据的新数组对象。

解决方法:

采用 reduce() 处理数组元素,达到最终目的;

  • reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值;
  • reduce()可以作为一个高阶函数,用于函数的 compose;
注意

reduce()对于空数组是 不会 执行回调函数

语法:

代码示例
array.reduce(function(total,currentValue, currentIndex, arr),initialValue)
  • 参数列表:

    参数描述
    total必需。初始值,或者计算结束后的返回值。
    currentValue必需。当前元素。
    currentIndex可选。当前元素索引
    arr可选。当前元素所属的数组对象
    initialValue可选。传递给函数的初始值

实现代码:(过滤数组对象中的重复元素)

代码示例
const filterArray = (array) => {
    let tmp = {};
    let tmpArray = array.reduce((total, item) => {
        tmp[item.id] ? "" : (tmp[item.id] = total.push(item));
        return total;
    }, []);
    return tmpArray;
};

实例使用:

代码示例
// 使用
let testArray = [{
	id: 1,
	name: 'zhangsan'
}, {
	id,
	2,
	name: 'lisi'
}, {
	id: 1,
	'zhangsan'
}, {
	id: 4,
	name: 'wangwu'
}];
// 过滤后数据
let newArray = filterArray(testArray);

newArray = [{
	id: 1,
	name: 'zhangsan'
}, {
	id,
	2,
	name: 'lisi'
}, {
	id: 4,
	name: 'wangwu'
}];