How to store a dividend in a new array using javascript

I am trying to save numbers that are divided by three in a threes array. How it's 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(); 
+5
source share
4 answers

There were a few problems.

  • You needed to access the number in the array using the numbers[i] index, and not just check the index.

  • You also need to pass 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 an additional note, you can simplify your code using the .filter() method.

If the logical num % 3 === 0 true, then the number is not 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] 
+1
source

you put brackets around i when you click. You do not need parentheses.

 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 }; 
+1
source

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); 
+1
source

Try replacing the for loop for..in loop; using numbers[i] number in the array instead of [i] index of the element inside the array in the 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) 
+1
source

Source: https://habr.com/ru/post/1236481/


All Articles