Javascript loop an array to find numbers divisible by 3

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

提交回复
热议问题