2

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); });
asked Oct 5, 2022 at 18:54
0

2 Answers 2

3

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
2
  • It would take me months to get there, being a self-taught. Thanks! Commented Oct 5, 2022 at 18:58
  • 1
    Glad to help. Here's more info on reduce(), if it helps. Commented Oct 5, 2022 at 19:00
1

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);

answered Oct 5, 2022 at 19:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.