Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
107
rated 0 times [  114] [ 7]  / answers: 1 / hits: 40927  / 5 Years ago, tue, january 15, 2019, 12:00:00

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


More From » function

 Answers
18

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]




[#52769] Wednesday, January 9, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaceyr

Total Points: 510
Total Questions: 97
Total Answers: 116

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
kaceyr questions
;