Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Callback function from map() always returns same output

I am counting the number of divisors for every number in the list and wrote a separate function which works fine on its own. But when I use the function as a callback to map(), it fails miserably, always returning 1.

let list = [641, 976, 517, 263, 136, 270, 941, 
    400, 915, 790, 539, 414, 816, 546, 675,548, 299,
    812, 45, 432, 392, 178, 310, 439, 956, 319, 450,
    566, 72, 74, 715, 336, 723, 854, 472, 996, 604, 
    861, 182, 609, 117, 484, 358, 1000, 363, 237, 
    111, 629, 759, 505, 510];
 
list.map(num => countDivisors(num))
 
function countDivisors(n) {
  let numberOfDivisors = 0;

  for (let i = 1; i <= n; i++) {
    if (n % i == 0) {
      numberOfDivisors++;
    }
    return numberOfDivisors;
  }
}

How can this be fixed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are returning in the for-loop, you should return the result before the function ends and after the loop as:

You can also pass function as

list.map(countDivisors);

There is no need to take num as input and then pass the num to countDivisors

let list = [
  641, 976, 517, 263, 136, 270, 941, 400, 915, 790, 539, 414, 816, 546, 675,
  548, 299, 812, 45, 432, 392, 178, 310, 439, 956, 319, 450, 566, 72, 74, 715,
  336, 723, 854, 472, 996, 604, 861, 182, 609, 117, 484, 358, 1000, 363, 237,
  111, 629, 759, 505, 510,
];

list.map((num) => countDivisors(num));

function countDivisors(n) {
  let numberOfDivisors = 0;

  for (let i = 1; i <= n; i++) {
    if (n % i == 0) {
      numberOfDivisors++;
    }
  }
  return numberOfDivisors;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading