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

Sign up to request clarification or add additional context in comments.

2 Comments

It would take me months to get there, being a self-taught. Thanks!
Glad to help. Here's more info on reduce(), if it helps.
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);

Comments

Your Answer

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.