Reputation: 31
var array = [3, 4, 6, 5, 9, 10, 21];
var divThree = [];
var loveTheThrees = function (array) {
for (i = 0; i = array.length; i++) {
if (array[i] % 3 === 0) {
amount.push(divThree[i]);
}
}
}
I am just learning Javascript and having a bit of trouble with this function. I can feel im close but cant figure out what im doing wrong.
Upvotes: 2
Views: 2351
Reputation: 4113
There are different ways of going about it (as evidenced by the other answers here), but the bug in the code you posted is that the i = array.length
is resetting the value of i
. You'll want to use a <
instead. You also need to push into the proper array.
var array = [3, 4, 6, 5, 9, 10, 21];
var divThree = [];
var loveTheThrees = function (array) {
for (i = 0; i < array.length; i++) {
if (array[i] % 3 === 0) {
divThree.push(array[i]);
}
}
}
Upvotes: 1
Reputation: 68645
In your code you are assign i = array.length
instead of a condition, so your loop is infinite. You need to change =
into the <
. And also push into the dimThree
not to amount
.
var array = [3, 4, 6, 5, 9, 10, 21];
var divThree = [];
var loveTheThrees = function (array) {
for (i = 0; i < array.length; i++) {
if (array[i] % 3 === 0) {
divThree.push(array[i]);
}
}
}
loveTheThrees(array);
divThree.forEach(x => console.log(x));
Or use filter()
function
var array = [3, 4, 6, 5, 9, 10, 21];
var divThree = [];
divThree = array.filter(x => x % 3 === 0);
divThree.forEach(x => console.log(x));
Upvotes: 1
Reputation: 3812
You first need to correct the for-loop condition from i=array.length
to i < array.length
. But even more important in this case - you need to consider the following:
You want to add/push the values that are divisible by 3 into an array called divThree
- so the correct syntax is <destination-array>.push(<value-to-push>)
. So in this case, if the current value array[i]
is divisible by three you want to push it into the array called divThree
so you do something like this:
for (i = 0; i < array.length; i++) {
if (array[i] % 3 === 0) {
//here we push array[i] into the array because it is divisible my 3
divThree.push(array[i]);
}
}
As you progress in your Javascript, you will find that in this case, it is easier to use lodash (for NodeJS apps) as it provides very nice convenience functions of these kinds of things.
I hope this helps.
Upvotes: 0
Reputation: 896
you will have to push the right value:
divThree.push(array[i]);
and: you can implement a for loop like:
for (var i = 0; i < array.length; i++) { .. }
or
for (var i = 0, l = array.length; i<l; i++) { .. }
Upvotes: 0
Reputation: 7742
You can use .filter
of array
var array = [3, 4, 6, 5, 9, 10, 21];
var output = array.filter(function(num){
return num%3 ==0
});
console.log(output);
Upvotes: 1