-1

I want to use map method on array with callback to another function. Everything seems to be working fine, but at the end returning values are not affected. I don't know what seems to be the problem.

var arr=[4,5,3,2];

function multi (x,callback){
 return callback(x*2); 
}

function add(x){
// alert(x);   when I'm alerting "x" here, it's value is multiplied as it should be
return x+3;  

}
var final=arr.map(function(a){multi(a,add); return a;});
final; // returns same values as Array "arr"
norbidrak
  • 463
  • 6
  • 22

3 Answers3

2

Your callback function returns a, which is the same element as passed in to it. Therefore the result is the same as the input.

To get the expected output you should instead return the modified result, e.g.

var final=arr.map(function(a){return multi(a,add);});
Jon
  • 428,835
  • 81
  • 738
  • 806
2

You forgot to return the value back

var arr = [4, 5, 3, 2];

function multi(x, callback) {
  return callback(x * 2);
}

function add(x) {
  return x + 3;

}
var final = arr.map(function(a) {
  return multi(a, add);
});

console.log(final)
Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70
1

You need to return the value from the callback

function multi(x, callback) {
    return callback(x * 2);
}

function add(x) {
    return x + 3;
}

var arr = [4, 5, 3, 2],
    final = arr.map(function (a) { return multi(a, add); });
    //                             ^^^^^^
    
console.log(final);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392