Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store divisible number in a new array with javascript

Tags:

javascript

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();
like image 793
user3713354 Avatar asked Sep 26 '22 03:09

user3713354


2 Answers

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]
like image 180
Josh Crozier Avatar answered Oct 12 '22 23:10

Josh Crozier


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
};
like image 28
KPrince36 Avatar answered Oct 13 '22 01:10

KPrince36