'Javascript : Using .reduce and passing in a function to add strings

I'm trying to use the .reduce method passing in a function and an initial value 'Stack' but I've been getting undefined.

I added a console.log in the reduce method to see what may be going wrong, and it seems to be related to the accumulator, which keeps returning undefined, but I can't understand why.

Thank you for your assistance.

function addingSpace(string1, string2){
  let result = string1 + " " + string2;
  return result;
}

function combineStr(array, callback, iv){
  let result = array.reduce((acc, cv) => {
    callback(acc, cv)
  }, iv);
  return result;
}

let testArr = ['flow', 'is', 'amazing']
console.log(combineStr(testArr, addingSpace, 'Stack')) // 'Stack flow is amazing'



Solution 1:[1]

To further expand on my comment, the callback function you’re using in Array.prototype.reduce isn’t returning anything, so it defaults to returning undefined.

You will need to return the value so that the accumulator is updated for the next iteration:

return callback(acc, cv);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Terry