Given the array below, how can I return the element containing the max number?
JavaScript
x
2
1
let ar = [["finalOrderData",1],["finalFabricData",3],["finalDecorationData",3],["finalHtData",3]]
2
Expected Result
JavaScript
1
2
1
let ar = ["finalFabricData",3]
2
This is the function I’m trying with, but it only returns the number itself:
JavaScript
1
4
1
function getMaxOf2DIndex(arr, idx) {
2
return Math.max.apply(null, arr.map(function (e) { return e[idx] }))
3
}
4
Appreciate any help!
Advertisement
Answer
Use Array.sort()
:
JavaScript
1
5
1
let ar = [['finalOrderData', 1], ['finalFabricData', 3], ['finalDecorationData', 3], ['finalHtData', 3]];
2
3
let res = ar.sort((a, b) => b[1] - a[1])[0];
4
5
console.log(res);
Note that this doesn’t handle the alphabetical order of the word.