0

I want to find the max number among the first and second elements of each array inside the array of arrays separately:

function largestOfElements(mainArray) {
  return mainArray.map(function(subArray) {
    return subArray.reduce(function(previousLargestNumber, currentLargestNumber) {
      return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber;
    }, 0);
  });
}
console.log(largestOfElements([
  [],
  [13, 47],
  [38, 35],
  [24, 34]
]));
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

the current way returns an array of the largest numbers in each array. How can I return the largest of the first elements and the largest of the second elements? the expected result will be:

[38, 47]

2 Answers 2

2

You can use the function reduce.

  • The initial value for the function reduce are the min values to start getting the highest values.
  • Check for the length of the current array.
  • Use destructuring assignment to get the first and second value [first, second].
  • Check the current value against first and second respectively to get the highest.

var array = [
  [],
  [13, 47],
  [38, 35],
  [24, 34]
];

var result = Object.values(array.reduce((a, c) => {
  if (c.length) {
    var [first, second] = c;
    if (first > a.f) a.f = first;
    if (second > a.s) a.s = second;
  }
  
  return a;
}, {f: Number.MIN_VALUE, s: Number.MIN_VALUE}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

could you add more explanation please?
0

var array = [
  [],
  [13, 47],
  [38, 35],
  [24, 34]
];

console.log([0,1].map(i => Math.max(...array.map(v => v[i]).filter(v => v))));

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.