5

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();
  • See [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/q/500504/1529630) – Oriol Nov 21 '15 at 01:05

4 Answers4

1

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]
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

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
};
KPrince36
  • 2,886
  • 2
  • 21
  • 29
1

Here you go:

var numbers = [1,2,3,4,5,6,7,8,9];
function iLoveThree(numbers) {
  return numbers.filter(function(n) {
    return n % 3 === 0;
  });
}
var threes = iLoveThree(numbers);
Hunan Rostomyan
  • 2,176
  • 2
  • 22
  • 31
1

Try substituting for loop for..in loop ; using numbers[i] number in array instead of [i] index of item within array in current iteration

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

var threes = [];

for(var i = 0; i < numbers.length; i++)
  !(numbers[i] % 3) && threes.push(numbers[i]);

console.log(threes)
guest271314
  • 1
  • 15
  • 104
  • 177