Code review: Return Largest Numbers in Arrays

While I’m on my way to finish my JS course, I’m able to figure out the algorithm to return largest numbers in arrays.

I don’t know if my post is/can against rule to post an answer.

The code
function largestOfFour(arr) {
  let largest = [];
  for (let i = 0; i < arr.length; i++) {
    let arr2 = arr[i];
    for (let j = 0; j < arr2.length; j++) {
      if (arr2.reduce((a, b) => a > b ? a : b)) {
        largest.push(arr2.reduce((a, b) => a > b ? a : b));
        break;
      }
    }
  }
  console.log(largest);
  return largest;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

It’s just the only way or my code is not simple enough especially for the reduce function?

Hi. What task is it?

Return an array of largest number from given array. I edited the code, you can see it.

You may use arr.reduce() here to form the resulting array. Also, there is a shorter syntax of finding max number: Math.max() + spread array. Also, you may form new array using […arr, someVal]. Try to solve it with one line of code.
I’d do it something like that:

function largestOfFour(arr) {
  return arr.reduce((acc, val) => [...acc, Math.max(...val)], []);
}

Can you explain what each part is doing and why? Before worrying too much about ‘optimization’, I’d think of clarity and simplicity. You have some optimization errors that arguably are simplicity errors.

Maybe I mislead by using “optimization”. I just want review of my code for more a simpler code.

This is still where you need to start.

  1. First, initialize largest array. This variable will be used to return array of largest number
  2. First loop loops 1st dimension of array, then save its value to a new array named arr2.
  3. Second loop loops 2nd dimension of array from arr2.
  4. If by reduce of new array resulted in largest number, then push it to largest.
  5. To prevent the largest number looped four times (the four came from length of arr2), break it once it’s found.

I used loops because to me it’s much more understandable

But a reduce is also a loop, so you have 4 loops.

Hold on, I just realized it! I forgot that reduce is a loop too!

Realized that I used too much loop, I can just simply use reduce().

By the way, that is good one-line code.

code…cataphotoApp level 6

If you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

Thank you.

1 Like