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));
Output
[ 33, 9, 78, 12, 18 ]