Javascript function for finding multiples of a number

  • A+

Create a function called mulitples0f It will accept two arguments, the first will be an array of numbers, the second will be a number. The function should return a new array that is made up of every number from the argument array that is a multiple of the argument number. So multiplesOf([5,6,7,8,9,10],3) will return [6,9]

function multiplesOf(numbers) {   var multiples = numbers[0];    for (var i = 0; i < numbers.length; i++) {     if (numbers[i] % multiples === 0) {       multiples = numbers[i];     }   }    return multiples; }  console.log(multiplesOf([4, 5, 6, 7, 8], 2));

says function is defined in jsbin help please


You have a few issues with your code. At the moment multiplesOf only accepts 1 argument when it should be two, ie, the numbers array and a single number

Your other issue is that you are not keeping an array of the multiples found, instead, you are setting a variable to the multiples found and is getting overwritten when a new multiple if found (thus leaving you with the very last multiple found in the array). Instead, you want to change your multiples variable to an array. This way you can push every multiple found into this array.

See working example below (read code comments for changes):

function multiplesOf(numbers, number) { // add second argument   var multiples = []; // change to array (so that we can store multiple numbers - not just one multiple)   for (var i = 0; i < numbers.length; i++) {     if (numbers[i] % number === 0) { // divide by the number       multiples.push(numbers[i]); // add the current multiple found to the multiples array     }   }    return multiples; }  console.log(multiplesOf([4, 5, 6, 7, 8], 2)); // Output: [4, 6, 8]


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: