gpt4 book ai didi

javascript - 我想提取重复项中的最大值

转载 作者:行者123 更新时间:2023-12-01 15:23:58 24 4
gpt4 key购买 nike

我想删除重复的值,但我想选择长度最大值的那个。

let meary = [];
meary.push({ name: "aaa", value: 90, length: 3 });
meary.push({ name: "bbb", value: 90, length: 5 });
meary.push({ name: "ccc", value: 80, length: 3 });
meary.push({ name: "ddd", value: 0, length: 4 });
meary.push({ name: "eee", value: 0, length: 3 });
meary = meary.filter((ele, index, arr) => {
// 重複削除
const isa =
arr.findIndex((item) => {
if (item.value === ele.value) {
if (item.length > ele.length) {
return true;
}
}
return false;
}) === index;
return isa;
});
console.log(JSON.stringify(meary));

这是我想要的结果
[
{ name: "bbb", value: 90, length: 5 },
{ name: "ccc", value: 80, length: 3 },
{ name: "ddd", value: 0, length: 4 }
]

这是得到的实际结果
[]

如何编写代码以获得我想要的结果?

最佳答案

你可以filter排除那些具有相同值且长度小于 some 的项目数组中的其他项:

const meary = [];
meary.push({ name: "aaa", value: 90, length: 3 });
meary.push({ name: "bbb", value: 90, length: 5 });
meary.push({ name: "ccc", value: 80, length: 3 });
meary.push({ name: "ddd", value: 0, length: 4 });
meary.push({ name: "eee", value: 0, length: 3 });

const result = meary.filter(
(x, i, a) => !a.some(
(y, j) => x.value === y.value && x.length < y.length && i != j
)
);

console.log(result);

关于javascript - 我想提取重复项中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62013967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com