Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return the element of an array containing the max value (index 1) (Javascript)?

Given the array below, how can I return the element containing the max number?

let ar = [["finalOrderData",1],["finalFabricData",3],["finalDecorationData",3],["finalHtData",3]]

Expected Result

let ar = ["finalFabricData",3]

This is the function I’m trying with, but it only returns the number itself:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function getMaxOf2DIndex(arr, idx) {
  return Math.max.apply(null, arr.map(function (e) { return e[idx] }))
}

Appreciate any help!

>Solution :

Use Array.sort():

let ar = [['finalOrderData', 1], ['finalFabricData', 3], ['finalDecorationData', 3], ['finalHtData', 3]];

let res = ar.sort((a, b) => b[1] - a[1])[0];

console.log(res);

Note that this doesn’t handle the alphabetical order of the word.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading