Array.map

Posted by Joe Enos on January 04, 2021 · 5 mins read

Definition

[].map(function(currVal, idx, arr) { }[, thisArg]);

Sample Code

// Simple
var arr = ["a", "b", "c"];
var helloArr = arr.map(function(x) { return "Hello " + x; });
helloArr.forEach(console.log);

// Using thisArg
var item = { sum: 0 };
var newArray = [1,2,3].map(function(x) { this.sum += x; return x * 10; }, item);
console.log(item.sum); // 6
console.log(newArray); // [10,20,30]

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Polyfill

if (!Array.prototype.map) {
Array.prototype.map = function(callback/*, thisArg*/) {
var T, A, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = arguments[1];
}
A = new Array(len);
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
kValue = O[k];
mappedValue = callback.call(T, kValue, k, O);
A[k] = mappedValue;
}
k++;
}
return A;
};
}

View Code on GitHub