JS: Array.prototype.map

By Xah Lee. Date: . Last updated: .

Apply function f to every element of the array arrayX. Return the new array. Original array is not changed.

If thisArg is given, it will be used as this value of f. If it is not given, undefined is used.

[see “this” Binding]

The function f is passed 3 args: • current_elementcurrent_indexarrayX.

const a1 = [3,4,5];
const a2 = a1.map( ((x) => (x+1)) );

console.log(a2);  // [ 4, 5, 6 ]

// original is not changed
console.log(a1);  // [ 3, 4, 5 ]

Example of using Array.prototype.map, with the passed function using more than 1 argument.

// example of using Array.prototype.map, with the passed function using more than 1 arg

const a1 = ["a", "b", "c"];

const a2 = a1.map(
    ((x,i,ar) => (console.log ( x, i, ar )))
);

// prints
// a 0 [ 'a', 'b', 'c' ]
// b 1 [ 'a', 'b', 'c' ]
// c 2 [ 'a', 'b', 'c' ]

Using Second Argument

This code shows what does it do:

// example of using Array.prototype.map with second argument

const a1 = [3,4,5];

const obj = { "jj":9 };

a1.map( function (x) { console.log ( x , this ); }, obj );

// prints

// 3 { jj: 9 }
// 4 { jj: 9 }
// 5 { jj: 9 }

This code shows a example:

// example of using map with a second arg

const ff = function (x) {
// add a property to the object this function is context of
this[x.toString()] = x+1;
return x+1;
}

// new object
var jj = {};

// array
var a1 = [1,2,3];

// map ff to a1, with context jj
var a2 = a1.map(ff, jj);

// new array value
console.log (a2); // [ 2, 3, 4 ]

// jj is changed
console.log (jj); // { '1': 2, '2': 3, '3': 4 }

[see Array.prototype.forEach]

Buy JavaScript in Depth

JavaScript in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype