Home > Software engineering >  JavaScript finding the highest value in array of arrays and printing the winning array
JavaScript finding the highest value in array of arrays and printing the winning array

Time:09-16

I went through multiple StackOverflow answers and googled thoroughly before coming in here to help.

I have an array which includes arrays, as shown below.

Please how would I go about finding an array with the highest first value, in this example 30 and print out the whole array which includes the highest value as the result, so in this case the answer is [ 30, '0.26', [ 'oranges', 'with apples' ], [ 'bananas', 'with apples' ] ] ?

I know how to get the highest value, but I can't figure out how to print the whole array including the highest value.

Thank you!!

 let arr = [
     [
        10,
        '0.07',
        [ 'oranges', 'with apples' ],
        [ 'bananas', 'with apples' ]
      ],
      [
        20,
        '0.15',
        [ 'oranges', 'with apples' ],
        [ 'bananas', 'with apples' ]
      ]
      [
        30,
        '0.26',
        [ 'oranges', 'with apples' ],
        [ 'bananas', 'with apples' ]
      ]
    
    ]

CodePudding user response:

Found the answer:

const highest = arr.reduce((previous, current) => {
  return current[0] > previous[0] ? current : previous;
});

console.log(highest);

Source: https://daily-dev-tips.com/posts/javascript-find-min-max-from-array-of-arrays/

CodePudding user response:

You will need to scan the array and find out the index which contains the highest number

max = -100//You can do something like negative infinity
highestIndex = null;

arr.forEach((arrayToSearch, index) => {

if(arrayToSearch[0] > max) {
highestIndex = index
}


})

Now hopefully you have the Element index which contains the max number you can just print it out...

arr[highestIndex].forEach(elem=>console.log(elem))
  • Related