user1015388
user1015388

Reputation: 1515

how to find the max value and the previous max value in array

I have an array of objects. I want to find the max value and the one before that.

arr : [{key:1, value: 1},{key:2, value: 2}, {key:3, value: 3}, {key:4, value: 4}, {key:5, value: 5}]

    let largest = 0;
    greater = 0;
    val = [];
    this.arr.forEach(aa => {
      if (largest < Number(aa.value)) {
        largest = Number(aa.value);
        greater = aa.key;
      }
    });
  }

The value of greater is 5; I want to get the value 4 too and push both of them to val array.

Upvotes: 0

Views: 595

Answers (2)

आनंद
आनंद

Reputation: 2582

The best way to achieve the same is by using the Array prototype function sort().

What you need to do is sort in descending order and grab the first two elements.

MDN link for sort() documentation

Here's how I would write it.

let newArr = arr.sort(function(a, b){
                      return b.value-a.value;
                     });

Now you can grab the top two values in newArr.

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

Separate values of the array. Get the maximum value using Math.max, then filter your array and get another one which does not contain the max1 value from the first search and do the same on the filtered array.

const arr = [
     { key: 1, value: 1 },
     { key: 2, value: 2 }, 
     { key: 3, value: 3 }, 
     { key: 4, value: 4 }, 
     { key: 5, value: 5 }
];

const valuesMax1 = arr.map(item => item.value);
const max1 = Math.max(...valuesMax1);

const valuesMax2 = valuesMax1.filter(item => item !== max1);
const max2 = Math.max(...valuesMax2);

console.log(max1);
console.log(max2);

Another simple way is to sort array and get first two items

const arr = [
         { key: 1, value: 1 },
         { key: 2, value: 2 }, 
         { key: 3, value: 3 }, 
         { key: 4, value: 4 }, 
         { key: 5, value: 5 }
];

const sorted = arr.sort((f,s) => s.value - f.value);

console.log(sorted[0].value);
console.log(sorted[1].value);

Upvotes: 0

Related Questions