Skip to content
Advertisement

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:

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

Appreciate any help!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement