常见的数组去重主要有俩方面:
- 由基本类型组成的数组去重
- 由对象组成的数组根据对象某个属性去重
基本类型去重:
export function unique(array) {
const arr = []
const contain = {}
array.forEach(item => {
if (!contain.hasOwnProperty(item)) {
arr.push(item)
contain[item] = true
}
})
return arr
}
效果:
根据对象属性去重:
/**
*
* @param {Array} array
* @param {string} key ,对象属性名
* @returns {Array}
*/
export function uniqueByAttr(array, key) {
const hash = {};
const arr = array.reduce((preVal, curVal) => {
hash[curVal[key]]
? ""
: (hash[curVal[key]] = true && preVal.push(curVal));
return preVal;
}, []);
return arr;
}
效果:
脚踏实地行,海阔天空飞