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); });
CodePudding user response:
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);
CodePudding user response:
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);