Javascript loop an array to find numbers divisible by 3

前端 未结 8 1134
清歌不尽
清歌不尽 2021-01-25 05:41

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

相关标签:
8条回答
  • 2021-01-25 06:31

    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

    0 讨论(0)
  • 2021-01-25 06:31

    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;
        }
    
    0 讨论(0)
提交回复
热议问题