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?
>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;
}