Given the array below, how I can return the element whose first index contains the highest number:
let ar = [[1,24], [2, 6]]
I've tried many proposed solutions, but they return the number itself, while it should be, in the case above [2,6]
One of the solutions I've tried is, but it returns 24, 6
:
var maxRow = arr.map(function(row){ return Math.max.apply(Math, row); });
2 Answers 2
To do what you require you can use reduce()
to compare the values of the first item in each child array and return the one with the highest value:
let ar = [[1,24], [2, 6]]
let result = ar.reduce((acc, cur) => acc[0] < cur[0] ? cur : acc);
console.log(result);
answered Oct 5, 2022 at 18:57
-
It would take me months to get there, being a self-taught. Thanks!onit– onit2022年10月05日 18:58:30 +00:00Commented Oct 5, 2022 at 18:58
-
1Glad to help. Here's more info on
reduce()
, if it helps.Rory McCrossan– Rory McCrossan2022年10月05日 19:00:01 +00:00Commented Oct 5, 2022 at 19:00
One way is using a reduce. Try like this:
const ar = [
[1,24],
[2, 6],
];
const biggest = ar.reduce(
(acc, cur) => cur[0] > (acc?.[0] || 0) ? cur : acc,
[],
);
console.log(biggest);
lang-js