JavaScript Array.prototype.map()

Array.prototype.map() is one of the core functions of the functional programmer’s toolkit, together with filter(), and reduce(). They take a function as input and return an output with zero side effects. I.E, each time it’s called, a new array is created and returned. The existing array is not modified.

They take functions as inputs, often in the form of anonymous functions or callback functions; they iterate over the array and apply the function to each item in the array.

NB: They only work on arrays, they don’t work on other iterable data structures, like certain objects. However other libraries like underscore.js, Lazy.js, stream.js and many more all implement their own map(), filter(), and reduce() methods that are more versatile.

Syntax

arr.map(callback [, thisArg]);

Parameters:

  • callback(): this function produces an element for the new array, receiving these arguments:

currentValue: This argument gives the current element being processed in the array

index: This argument gives the index of the current element in the array
 — array: This argument gives the array being processed

  • thisArg(): This function is optional. The value is used as this when executing the callback.

Example 1: Using currentValue

var w = "Here we look at the probability of a word in this sentence"
console.log(w.split(' ').map(function(s){
s = s[0].toUpperCase() + s.substr(1);
return s
}))
>>>Output: ["Here", "We", "Look", "At", "The", "Probability", "Of", "A", "Word", "In", "This", "Sentence"]

The code above takes a string w, turn it into an array of words by splitting it with .split(' '). It then it map through each word in the array and capitalizes the first letter of each word.

Example 2: Using currentValue and index

var n = [3,4,5,6];
console.log(n.map(function(s,i){
return s+i;
}));
>>>Output: [3, 5, 7, 9]

The code above takes an array of numbers n, maps each number sto the sum of the number and its index s+i.

Example 3: Using currentValue, index and array

# Reverse an array using map()
var reverse = function(arr){
return arr.map(function(x,i,a){
return a[a.length-1 - i]
});
}
var n = [3,4,5,6];
console.log(reverse(n))
>>Output: [6,5,4,3]

The code above inverts an array, such that the first element is now the last and the last is now the first.

NB: This can be achieved with Array.prototype.reverse

Like what you read? Give eyong kevin a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.