array.reduce()数组去重

JavaScript数组对象去重

需求:

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

解决方法:

采用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'
}];

猜你喜欢

转载自blog.csdn.net/SK_21/article/details/109226476
今日推荐