arr=[
{
maxDeptCode: "md3"
maxDeptName: "泡泡"
minDeptCode: "md301"
minDeptName: "泡泡少儿"
schoolId: 1
schoolName: "北京"
},
{
maxDeptCode: "md2"
maxDeptName: "中学"
minDeptCode: "md201"
minDeptName: "中学一对一"
schoolId: 1
schoolName: "北京"
},{
maxDeptCode: "md3"
maxDeptName: "泡泡"
minDeptCode: "md301"
minDeptName: "泡泡少儿"
schoolId: 1
schoolName: "北京"
},
]
1.方法一
function process(arr) {
// 缓存用于记录
const cache = [];
for (const t of arr) {
// 检查缓存中是否已经存在
if (cache.find(c => c.maxDeptCode === t.maxDeptCode && c.minDeptCode === t.minDeptCode)) {
// 已经存在说明以前记录过,现在这个就是多余的,直接忽略
continue;
}
// 不存在就说明以前没遇到过,把它记录下来
cache.push(t);
}
// 记录结果就是过滤后的结果
return cache;
}
2.方法二
function process2(arr) {
// 需要一个字典,可以用 Set/WeakSet 或者就简单的 JS 对象
const dict = {};
// 过滤的过程中完善 dict
return arr.filter(t => {
// 根据 max 和 min 来生成唯一识别的关键字
// 这里采用的办法是使用一个不会出现在两个数据中的字符 `|` 来连接
const key = [t.maxDeptCode, t.minDeptCode].join("|");
// 检查如果字典中已经存在,那这个数据就过滤掉,不需要了
if (dict[key]) {
return false;
}
// 如果字典不不存在,加入字典,同时把数据保留下来(返回 true)
dict[key] = true;
return true;
});
}
3.方法三
let result = arr.reduce((init, current) => {
const maxCode = current.maxDeptCode
const minCode = current.minDeptCode
const index = `${maxCode}${minCode}`
if (init.length === 0 || !init[index]) {
init[index] = current
}
return init
}, [])
console.log(result)