Is my solution any good for algo - Return Largest Numbers in Arrays

So this is a task:

Basic Algorithm Scripting: Return Largest Numbers in Arrays

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].

I solved this with a kinda simple code:

function largestOfFour(arr) {
let largest = [(Math.max(…arr[0])), (Math.max(…arr[1])),(Math.max(…arr[2])),(Math.max(…arr[3]))];

return largest;
}

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

But when I looked at other recommended solutions I saw none of the recommended solutions is anything similar to my code. Would this be considered a good practice in solving such problems or my code has a flaw? I understand that the real problem with my code is when we have more than 4 sub-arrays, but for this particular problem when we don’t have many sub-arrays is this a legit solution? Please take a note that I am a beginner and I am trying to understand JS as better as possible.

Thanks in advance for your answers.

1 Like

Your solution works in this particular challenge, based on the fact you are told in advance the provided array will contain exactly 4 sub-arrays. However, the other solutions take a more general approach which could be applied to arrays with a million sub arrays without having to hard-code anything like you have done (i.e. Math.max(…arr[1])). When ever you hard-code something, it becomes brittle and makes it difficult to reuse in other areas of your code. In general, try to make your functions as generic and flexible as possible. When you get to more advanced problems, you will thank yourself.

It takes lots of practice to learn how to create general purpose functions. Just keep practicing and trying different things and you will get there.

2 Likes

Nice attempt fanstebg. I totally agree with RandelIDawson. It’s not a good practice to hardcode solutions. Though I don’t get to see other solutions you guys talked about, probably because I am new to this platform and don’t know how to navigate myself well. However, I feel the solution can be optimized this way

const largestOfFour = arrs => arrs.map(arr => Math.max(...arr));

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

Feedback is also welcome. Thanks

It’s not a bad solution! In addition to what Randell said above, though, it’s also not the most efficient one. If you want something slightly faster, you could iterate through all of the arrays, maintain a max value by comparing it against each element in the arrays, and simply return the max value at the end. That way, you skip having to find the max of the maximums of each individual array.