2

New here and been trying to figure this out for a bit now. Can't seem to find the answer.

Problem: trying to separate all numbers from 5 upwards into a separate array "bigNumbers". All other numbers to "smallNumbers"

Here's what I have so far:

let allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 
let bigNumbers = []; 
let smallNumbers = [];

allNumbers.forEach(function (a) {
  if(allNumbers >= 5) {
    return allNumbers.push(bigNumbers);
  } else {
    return allNumbers.push(smallNumbers);
  }
});

Might be taking the wrong approach entirely here using the .push() method. Any feedback is appreciated.

5
  • Read the code.... Look at it closely First allNumbers >= 5 you are comparing an array to be greater than five. and then you have allNumbers.push(bigNumbers); You are pushing the bigNumbers array into the allNumbers array. You are not pushing a value into the array. Learn basic debugging console.log(allNumbers,5, allNumbers>=5) that will show you what is happening on the if. Commented Nov 26, 2019 at 17:34
  • try bigNumbers .push(a); and smallNumbers.push(a) instead. and check if (a >= 5) instead as well Commented Nov 26, 2019 at 17:35
  • Inside your .forEach() callback you should be referring to a, not allNumbers Commented Nov 26, 2019 at 17:35
  • remove return and also change the if to check a Commented Nov 26, 2019 at 17:35
  • Right return is pointless because .forEach() ignores return values. Commented Nov 26, 2019 at 17:36

2 Answers 2

4

You're testing the wrong variable, it should be a, not allNumbers. And the argument to .push() is the value you want to push onto the array, not the array to push onto. There's also no need to use return, since forEach doesn't use the return values.

let allNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; 
let bigNumbers = []; 
let smallNumbers = [];

allNumbers.forEach(function (a) {
  if(a >= 5) {
     bigNumbers.push(a);
  } else {
     smallNumbers.push(a);
  }
});

console.log("Big: " + JSON.stringify(bigNumbers));
console.log("Small: " + JSON.stringify(smallNumbers));

Sign up to request clarification or add additional context in comments.

Comments

0

Trouble is in your if (allNumbers >= 5)

What you want is to know if the current number being iterated is greater than 5:

if (a >= 5)...

2 Comments

There are more problems than just the comparison.
Right, return is not necessary in forEach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.