Javascript — Writing Map as a Recursive Function

The Map Function

const myArray = [1,2,3,4,5]const newArray = myArray.map(arrayItem => arrayItem + 1)console.log(newArray) // [2,3,4,5,6]
const map = (arr, callback) => {  //create a new array
const newArray = []
//loop over the array passed to the function
for (let index = 0; index < arr.length; index += 1){
//Push the result of the callback into the new array
newArray.push(callback(arr[index], index))
}
//after done looping, return the resulting array
return newArray
}

Recursive Functions

const map = (oldArray, callback, newArray = []) => {    //base case: check if there are any items left in the original array to process
if (oldArray.length <= 0){
//if all items have been processed return the new array
return newArray
} else {
//destructure the first item from old array and put remaining in a separate array
const [item, ...theRest] = oldArray
// create an array of the current new array and the result of the current item and the callback function
const interimArray = [...newArray, callback(item)]
// return a recursive call to to map to process the next item.
return map(theRest, callback, interimArray)
}
} console.log(map([1,2,3,4,5,6], x => x+1))

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store