Javascript loop an array to find numbers divisible by 3

前端 未结 8 1133
清歌不尽
清歌不尽 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:15

    loveTheThrees=(arr)=>arr.filter(el=>Boolean(parseFloat(el)) && isFinite(el) && !Boolean(el%3))

    es6 version + skipping non numbers

    loveTheThrees([null,undefined,'haha',100,3,6])

    Result: [3,6]

    0 讨论(0)
  • 2021-01-25 06:15
    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);
    
    0 讨论(0)
  • 2021-01-25 06:19
    var array = [],
    three = [];
    
    function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
        if(array[i] % 3 == 0){
            three.push(array[i]);
         }
       }
     }
    
    0 讨论(0)
  • 2021-01-25 06:20

    You can use Array#filter for this task.

    filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

    function loveTheThrees(array) {
        return array.filter(function (a) {
            return !(a % 3);
        });
    }
    document.write('<pre>' + JSON.stringify(loveTheThrees([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 0, 4) + '</pre>');

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

    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]);
         }
      }
    
    0 讨论(0)
  • 2021-01-25 06:29

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