Javascript loop an array to find numbers divisible

2020-04-19 05:15发布

I am needing to find the correct way to have javascript loop through an array, find all numbers that are divisible by 3, and push those numbers into a new array.

Here is what I have so far..

var array = [],
    threes = [];

function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
    threes = array.push(i % 3);
  }
  return threes;
}

So if we pass through an array of [1, 2, 3, 4, 5, 6] through the function, it would push out the numbers 3 and 6 into the "threes" array. Hopefully this makes sense.

8条回答
何必那么认真
2楼-- · 2020-04-19 05:54
var array = [],
three = [];

function loveTheThrees(array) {
for (i = 0, len = array.length; i < len; i++) {
    if(array[i] % 3 == 0){
        three.push(array[i]);
     }
   }
 }
查看更多
霸刀☆藐视天下
3楼-- · 2020-04-19 05:57

Using Filter like suggested by Nina is defiantly the better way to do this. However Im assuming you are a beginner and may not understand callbacks yet, In this case this function will work:

function loveTheThrees(collection){
        var newArray = []
        for (var i =0; i< collection.length;i++){
            if (myArray[i] % 3 === 0){
                newArray.push(collection[i])
            }
        }
        return newArray;
    }
查看更多
Juvenile、少年°
4楼-- · 2020-04-19 06:02
var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function loveTheThrees(array1) {
  var threes = [];
  for (var i = 0; i < array1.length; i++) {
    if (array1[i] % 3 === 0) {
      threes.push(array1[i]);
    }
  }
  return threes;
}
loveTheThrees(originalArray);
查看更多
三岁会撩人
5楼-- · 2020-04-19 06:02

In ES6:

const arr = [1, 33, 54, 30, 11, 203, 323, 100, 9];

// This single line function allow you to do it:
const isDivisibleBy3 = arr => arr.filter(val => val % 3 == 0);


console.log(isDivisibleBy3(arr));
// The console output is [ 33, 54, 30, 9 ]
查看更多
萌系小妹纸
6楼-- · 2020-04-19 06:07

Check if the number is divisible by 3 if so then add it to array. Try this

function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
      if(array[i] % 3 == 0){
        three.push(array[I]);
     }
  }
查看更多
聊天终结者
7楼-- · 2020-04-19 06:13

console.log([1, 2, 3, 4, 5, 6, 7].filter(function(a){return a%3===0;}));

Array.filter() iterates over array and move current object to another array if callback returns true. In this case I have written a callback which returns true if it is divisible by three so only those items will be added to different array

查看更多
登录 后发表回答