Array.map

map — Creates a new array with the values returned from the callback.

Description

Array.map(function callback, [object this])

Parameters

Name Description Type Default Optional
callback See callback below. function No
this object Yes
callback

The following parameters is passed to the callback.

value

The value of the current index.

index

The current index.

array

The array.

Return values

Returns a new array with the return values from the callback.

Examples

Example #1 – map example
var array = [2, 4, 8]; var result = array.map(function () { console.log(this); return true; }); console.log(result); // [true, true, true] console.log(array); // [2, 4, 8]
var arr = [2, 4, 8]; var result = arr.map(function (value, index, array) { console.log(value, index, array); return true; }); console.log(result); // [true, true, true] console.log(arr); // [2, 4, 8]

Passing in a custom object for this.

var array = [2, 4, 8]; var result = array.map(function () { console.log(this); return true; }, document.location); console.log(result); // [true, true, true] console.log(array); // [2, 4, 8]

False for 4

var array = [2, 4, 8]; var result = array.map(function (value) { if (value === 4) { return false; } return true; }); console.log(result); // [true, false, true] console.log(array); // [2, 4, 8]

Return false for all.

var array = [2, 4, 8]; var result = array.map(function (value) { console.log(value); return false; }); console.log(result); // [false, false, false] console.log(array); // [2, 4, 8]

Return a new array with values doubled of the input.

var array = [2, 4, 8]; var result = array.map(function (value) { console.log(value); return value * 2; }); console.log(result); // [4, 8, 16] console.log(array); // [2, 4, 8]

External references