divisibleBy() function over array in JavaScript

Problem

We are required to write a JavaScript function that takes in an array of numbers and a single number as two arguments.

Our function should filter the array to contain only those numbers that are divisible by the number provided as second argument and return the filtered array.

Example

Following is the code ?

const arr = [56, 33, 2, 4, 9, 78, 12, 18];
const num = 3;

const divisibleBy = (arr = [], num = 1) => {
    const canDivide = (a, b) => a % b === 0;
    const res = arr.filter(el => {
        return canDivide(el, num);
    });
    return res;
};

console.log(divisibleBy(arr, num));
[ 33, 9, 78, 12, 18 ]

How It Works

The function uses the modulo operator (%) to check divisibility. When a number is divisible by another, the remainder is 0. The filter() method creates a new array containing only elements that pass the divisibility test.

Simplified Version

We can make the function more concise by removing the helper function:

const arr = [56, 33, 2, 4, 9, 78, 12, 18];
const num = 2;

const divisibleBy = (arr = [], num = 1) => {
    return arr.filter(element => element % num === 0);
};

console.log(divisibleBy(arr, num));
[ 56, 2, 4, 78, 12, 18 ]

Edge Cases

The function handles edge cases with default parameters:

// Empty array
console.log(divisibleBy([], 3));

// Division by 1 (default)
console.log(divisibleBy([5, 10, 15]));

// No divisible numbers
console.log(divisibleBy([1, 3, 7], 2));
[]
[ 5, 10, 15 ]
[]

Conclusion

The divisibleBy() function effectively filters arrays using the modulo operator and filter() method. Default parameters make it robust for handling edge cases like empty arrays.

Updated on: 2026-03-15T23:19:00+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements