Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function for finding multiples of a number

Create a function called multiplesOf.
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

like image 240
Dalton Avatar asked Oct 14 '25 07:10

Dalton


2 Answers

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]

Or, if you are happy to use a higher-order function, you can also use .filter() to get your new array. .filter() accepts a function as its first argument which takes an element as its argument. It will keep any of the elements which you return true for in your new array:

const multiplesOf = (numbers, number) => numbers.filter(n => !(n % number));
console.log(multiplesOf([4, 5, 6, 7, 8], 2)); // [4, 6, 8]
like image 64
Nick Parsons Avatar answered Oct 18 '25 05:10

Nick Parsons


You can use the filter method to achieve this:

const multiplesOf = (numbers, multiple) => {
return numbers.filter(x => x % multiple === 0);
}

console.log(multiplesOf([4, 5, 6, 7, 8], 2));

The filter method will return the array after filtering it with your specified condition which in our case is to check for a multiple.

You were also missing the 2nd argument to the function which is the multiple.

like image 30
Hussain Ali Akbar Avatar answered Oct 18 '25 05:10

Hussain Ali Akbar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!