let config = [{
name: 1,
state: 1,
output: 'Y',
}, {
name: 2,
state: 1,
output: 'A',
}, {
name: 1,
state: 100,
output: 'Y',
}, {
name: 2,
state: 100,
output: 'A',
}];
function unique(arr) {
const res = new Map();
return arr.filter((a) => !res.has(a.name) && res.set(a.name, 1))
}
console.log(unique(config))
先保留,后删除,
但是我需要后面的东西,而不是第一个。
我该如何保留它并删除第一个?
答案 0 :(得分:1)
Object.values
与Array#reduce
的组合
let config = [{
name: 1,
state: 1,
output: 'Y',
}, {
name: 2,
state: 1,
output: 'A',
}, {
name: 1,
state: 100,
output: 'Y',
}, {
name: 2,
state: 100,
output: 'A',
}];
let result = Object.values(config.reduce((acc, item) => (acc[item.name] = item, acc), {}));
console.log(result);