map callback function javascript code example

Example 1: javascript map

const myArray = ['Sam', 'Alice', 'Nick', 'Matt'];

// Appends text to each element of the array
const newArray = myArray.map(name => {
	return 'My name is ' + name; 
});
console.log(newArray); // ['My name is Sam', 'My Name is Alice', ...]

// Appends the index of each element with it's value
const anotherArray = myArray.map((value, index) => index + ": " + value);
console.log(anotherArray); // ['0: Sam', '1: Alice', '2: Nick', ...]

// Starting array is unchanged
console.log(myArray); // ['Sam', 'Alice', 'Nick', 'Matt']

Example 2: array map

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Example 3: arrow function map js

const exampleArray = ['aa','bbc','ccdd'];
console.log(exampleArray.map(a => a.length));
//Would print out [2,3,4]

Example 4: javascript map callback function

function doOpSingle2(arrelem,flag)
{
 // do something with one array element
}

var A = ["one", "two", "three", "four"];
var theFlag = util.getMask(); // call external function
var y = A.map(doOpSingle2(theFlag)); // this does not work!