JS: Array.prototype.map

By Xah Lee. Date: . Last updated: .

Apply function f to every element of the array myArray.

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 JS: “this” Binding]

The function f is passed 3 args: • current_elementcurrent_indexmyArray.

// example of Array.prototype.map
const a1 = [3,4,5];

const a2 = a1.map( ((x) => (x+1)) );

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

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

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 JS: Array.prototype.forEach]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials