2

我有一个重复的对象数组。我想删除这些重复项,但需要获取第三个键具有更高值的“重复项”。

尝试了这个解决方案:从 JavaScript 中的对象数组中删除重复项, 但这总是给我第一个重复项,我需要检查哪个具有更高的第三个键值。

let testArray = [
    { id: 1, value: "test1", value1: 1 },
    { id: 2, value: "test2", value1: 1 },
    { id: 1, value: "test3", value1: 5 }
];

let filtered = testArray.reduce((accumulator, current) => {
    if (!accumulator.find(({ id }) => id === current.id)) {
        accumulator.push(current);
    }
    return accumulator;
}, []);
console.log(filtered);

/* 
Result is:
[ { id: 1, value: 'test1', value1: 1 },
  { id: 2, value: 'test2', value1: 1 } ]

Result desired:
[ { id: 1, value: 'test1', value1: 5 },
  { id: 2, value: 'test2', value1: 1 } ]
*/

我期望结果如下:

[ { id: 1, value: 'test1', value1: 1 },
  { id: 2, value: 'test2', value1: 5 } ]

测试数组的

4

2 回答 2

2

您可以搜索索引,如果有效,则检查该值,如果该值更大,则更新数组。

let testArray = [
    { id: 1, value: "test1", value1: 1 },
    { id: 2, value: "test2", value1: 1 },
    { id: 1, value: "test3", value1: 5 }
];

let filtered = testArray.reduce((accumulator, current) => {
    let index = accumulator.findIndex(({ id }) => id === current.id)
    if (index === -1) {
        accumulator.push(current);
    } else if (accumulator[index].value1 < current.value1) {
        accumulator[index] = current;
    }
    return accumulator;
}, []);

console.log(filtered);

于 2019-07-22T15:55:36.047 回答
0

只需维护每个 id 对应的地图,如果现有值小于新值,则更新地图,Object.values()在地图上会给你想要的结果:

let testArray = [ { id: 1, value: "test1", value1: 1 }, { id: 2, value: "test2", value1: 1 }, { id: 1, value: "test3", value1: 5 } ];

let filtered = Object.values(testArray.reduce((acc, curr)=>{
  acc[curr.id] = acc[curr.id] && acc[curr.id].value1 > curr.value1 ?  acc[curr.id] : curr;
  return acc;
},{}));
console.log(filtered);

于 2019-07-22T15:59:51.497 回答