Reputation: 23
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.
Upvotes: 2
Views: 917
Reputation: 316
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)...
Upvotes: 0
Reputation: 781721
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));
Upvotes: 4