I want to remove duplicates of value, but I want to select the one with the maximum value of length.
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));
This is the result i want
[
{ name: "bbb", value: 90, length: 5 },
{ name: "ccc", value: 80, length: 3 },
{ name: "ddd", value: 0, length: 4 }
]
This is the actual result obtained
[]
How do I write the code to get the result I want?
The MAX function in Excel returns the highest value in a set of data that you specify. The syntax is as follows: MAX(number1, [number2], …) Where number can be represented by a numeric value, array, named range, a reference to a cell or range containing numbers.
If you want to remove all duplicates but leave the highest ones, you can apply this formula =MAX(IF($A$2:$A$12=D2,$B$2:$B$12)), remember to press Shift + Ctrl + Enter keys.
You can just filter out those items that have the same value and a smaller length than some other item in the array:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With