I am trying to store the numbers that are divisible by three in the threes array. How is this done?
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push([i]);
console.log(threes);
}
} return threes
};
iLoveThree();
There were a few problems.
You needed to access the number in the array using the index numbers[i]
rather than just checking the index.
You also needed to pass the two parameters to the iLoveThree
function.
Here is the working code:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var threes = [];
var iLoveThree = function (numbers, threes) {
for (i in numbers) {
if (numbers[i] % 3 === 0) {
threes.push(numbers[i]);
}
}
return threes;
};
console.log(iLoveThree(numbers, threes));
// [3, 6, 9]
As a side note, you could simplify your code by using the .filter()
method.
If the boolean num % 3 === 0
is true, then the number isn't removed from the array.
var numbers = [1,2,3,4,5,6,7,8,9].filter(function (num) {
return num % 3 === 0;
});
console.log(numbers);
// [3, 6, 9]
you put brackets around i
when you did the push. You do not need the brackets.
var numbers = [1,2,3,4,5,6,7,8,9];
var threes = [];
var iLoveThree = function(numbers,threes){
for(i in numbers){
if(i.value % 3 == 0){
threes.push(i); //don't put brackets here
console.log(threes);
}
} return threes
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With