Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to extract the maximum value among the duplicates

Tags:

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?

like image 295
otera Avatar asked May 26 '20 03:05

otera


People also ask

How do you find the highest value for duplicates in Excel?

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.

How do I get rid of duplicates in Excel but keep the highest value?

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.


1 Answers

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);
like image 106
Robby Cornelissen Avatar answered Sep 30 '22 21:09

Robby Cornelissen