Basic Algorithm Scripting - Return Largest Numbers in Arrays

Tell us what’s happening:

Hey folks, I found a solution to this problem and ended up checking the solutions just to be given different viewpoints on how you might approach the problem, and to my surprise, my solution was fairly different than most of them.

I checked out these resources to help me with this problem:

Your code so far

function largestOfFour(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
  let x = Math.max(...arr[i]);
  newArr.push(x);
  } 
  return newArr;
}

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


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

*/

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15

Challenge Information:

Basic Algorithm Scripting - Return Largest Numbers in Arrays

It’s great that you solved this but we’re trying to cut down on the number of solutions posted on the forum. If you want to post anything which is a spoiler for any of the FCC challenges, please put spoiler tags around the content. I’ve edited your post to spoiler your code. I’m glad you’re enjoying JS though - I had fun with that part of the curriculum too!

1 Like

Ok sorry about that, will do in future posted solutions!

Your version is pretty close to the map version, at least in logic if not syntax.

However, the map version in the hints is a little awkward because of the Function.apply.bind stuff.

You are more likely to see something like this I would think.

function largestOfFour(arr) {
  return arr.map((sub) => Math.max(...sub));
}

map does a lot of the work for you. It loops the array, creates a new array, and adds the element to it. And its return can be returned out of the function directly.

You “manually” loop the array, create a new array, and add the elements to it. Then return out that array.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.