In ES5, you can simply use the Array.prototype.filter()
method, combined with the remainder operator (%
), 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]
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.