How to Find Numbers Divisible by 'n' in a JavaScript Array of Numbers?

Keeping numbers in array that are divisible by a specified number in JavaScript

In ES5, you can simply use the Array.prototype.filter() method, combined with modulus, to filter out numbers that are not divisible by a specific number. For example, to only keep the numbers that are divisible by 3, you would do the following:

// ES5+
const nums = [1, 4, 6, 12, 15, 10, 22, 63];
const filteredNums = nums.filter((num) => num % 3 === 0);

console.log(filteredNums); // [6, 12, 15, 63]

If, at a minimum, you're unable to support ES5, then you may simply use a loop to filter out numbers divisible by a specific number. The example above can be re-written with a loop like so:

const nums = [1, 4, 6, 12, 15, 10, 22, 63];
const result = [];

for (let i = 0; i < nums.length; i++) {
    if (nums[i] % 3 === 0) {
        result.push(nums[i]);
    }
}

console.log(result); // [6, 12, 15, 63]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.