Return Largest Numbers in Arrays ...it works just fine in my console but not on the fcc website

I tried to solve this challenge, the solution I figured works really well on the console window of Chrome but not in the built in console of the website

function largestOfFour(arr) {
  let starter = 0;
  let i = 0;
  for (i = 0; i < arr.length; i++) {
    arr[i].forEach((el) => {
      if (el > starter) {
        return (starter = el);
      }
    });
  }
  arr.forEach((array) => {
    if (array.includes(starter)) {
      console.log(array);
    }
  });
}

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

Any help on what might be the problem?

Your function is supposed to return an array. Your function does not return anything.


Also.

forEach

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

1 Like

It should work that way then…

function largestOfFour(arr) {
let starter = 0;
let theOneArray;
for (let i = 0; i < arr.length; i++) {
arr[i].forEach((el) => {
if (el > starter) {
return (starter = el);
} else {
false;
}
});
}
arr.forEach((array) => {
if (array.includes(starter)) {
return (theOneArray = array);
} else {
false;
}
});
console.log(theOneArray);
}
largestOfFour([
[4, 5, 1, 3],
[13, 27, 18, 26],
[32, 35, 37, 39],
[1000, 1001, 857, 1],
]);

No, that code doesn’t work.

Try using a simple for loop first. No fancy looping methods. You can always refactor later to a fancy loop.

I think you have misunderstood how the forEach method works.

It is meant as a “fixed length” loop running side effects. You do not return values out of it. It is not a map or a filter.

Unlike map(), forEach() always returns undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.

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