简体   繁体   中英

JavaScript - implementing map function with reduce, error when passing function as argument

I am trying to implement a map function in javascript using reduce.

function newMap(inputArr, fn) {
    return inputArr.reduce((mapItem, elem) => 
        mapItem = (fn(elem)), [])
}

function plusTwo(num) {
    return num + 2;
}

newMap(arr, plusTwo())

console.log(newMap)

The error output is: "TypeError: fn is not a function"

So my question is -- what am I doing wrong that the reduce function signature or the function being passed is throwing an error?

PS -- still learning javascript, if someone could help edit the title for more clarity, that'd be much appreciated.

Thanks

You're calling plusTwo when passing it, but you need to only call plusTwo inside the reduce callback. Inside the reduce callback, add the call of fn(elem) onto the accumulator array.

 function newMap(inputArr, fn) { return inputArr.reduce((accum, item) => [...accum, fn(item)], []); } function plusTwo(num) { return num + 2; } const arr = [1, 2, 3]; console.log(newMap(arr, plusTwo));

The callback you pass to reduce is expected to return something. Plus what others commented, you want to pass plusTwo , not plusTwo() , which is a NaN (the result of undefined+2 ):

 function newMap(inputArr, fn) { return inputArr.reduce((accum, item) => { accum.push(fn(item)); return accum; }, []); } function plusTwo(num) { return num + 2; } const arr = [1, 2, 3]; console.log(newMap(arr, plusTwo)); console.log("plusTwo:", plusTwo); console.log("plusTwo():", plusTwo());

  • mapItem is the reference to the resulting array. You need to push the resulting value to it instead of reassigning it in every iteration, ie mapItem.push(fn(elem))
  • Pass in plusTwo as a function instead of invoking it plusTwo() , this is why you were getting the fn is not a function error
  • Print the result of newMap instead of newMap itself
function newMap(inputArr, fn) {
  return inputArr.reduce((mapItem, elem) => {
      mapItem.push(fn(elem))
      return mapItem;
  }, [])
}

function plusTwo(num) {
    return num + 2;
}

let result = newMap([1,2,3], plusTwo)

console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM