Why?
Recently I started doing something that I think is a lot of fun. Over thinking every problem I find. Exhaustively.
In this case, I was compelled by freeCodeCamp to "Return the Largest Numbers in Arrays". I just decided to see how many ways I could solve it. Really dive deep in to the MDN documentation for JavaScript Arrays to see what I could find. The problem at hand was this:
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
What'd I find?
I found four ways to solve the problem.
Array.map()
The first is using probably the most common method. Here I use Array.map()
to return an array of the highest value found by Math.max()
. It's short, it's sweet. If you're not aware, the map() function takes in a function that it applies to each of the elements of it's array.
largestOfFourRefactored([[1,2,3,4],[10,9,3,5],[100,101,95,92],[85,98,74,12])
// returns [4,10,101,98]
Nested Loops
The next is probably no surprise. It's really just Array.map()
in long hand. I use the first loop (i) to go through the four subarrays, then use the inner loop (j) to find the maximum value for each of them. After the inner loop, I use a bit of that new(ish) array destructuring to build up my output, and then finally return it. The output is the same as above. Much more difficult to read though.
Array.from()
I'll admit, I actually didn't know about Array.from()
until yesterday when I was writing this code. This method takes in an array like object as it's first parameter and then runs the supplied function on each of them. It then returns the resulting array.
The example that MDN gives looks like this:
Array.from([1,2,3], x => x * 2)
// [2,4,6]
So we can use it almost exactly like Array.map()
. But it was new to me, so I wanted to share it. It can also do this with strings, so you could use it to filter letters out of a string if you wanted.
Array.forEach()
This example sort of combines Array.map()
and the long hand form. I have to set aside an output
variable, and then return it. But then I have to push data in to the array from forEach()
. It works just as well as the others, and in a similar fashion.
Conclusion
I'll leave it up to you to decide which you like best. I personally prefer option one. It's so silky smooth and is easy to read. I know what I'm going to get from that right away. The others add in extra steps that aren't necessary... but do highlight the point that there are lots of ways to go about a problem.
I'd love to hear about it if you found other ways to do this problem. I'll definitely be posting more of these.
This post is based on a video from my YouTube channel
Top comments (0)