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.