map index js code example

Example 1: javascript map array

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: map javascript index

// Arrow function
map((element) => { ... } )
map((element, index) => { ... } )
map((element, index, array) => { ... } )

// Callback function
map(callbackFn)
map(callbackFn, thisArg)

// Inline callback function
map(function callbackFn(element) { ... })
map(function callbackFn(element, index) { ... })
map(function callbackFn(element, index, array){ ... })
map(function callbackFn(element, index, array) { ... }, thisArg)

Example 3: map index

array.map((currentelement, index) => {
	
});

Example 4: javascript map

function listFruits() {
  let fruits = ["apple", "cherry", "pear"]
  
  fruits.map((fruit, index) => {
    console.log(index, fruit)
  })
}

listFruits()

// https://jsfiddle.net/tmoreland/16qfpkgb/3/

Example 5: javascript map array

const sweetArray = [2, 3, 4, 5, 35]
const sweeterArray = sweetArray.map(sweetItem => {
    return sweetItem * 2
})

console.log(sweeterArray)

Example 6: array map

let A = [{ x:'x', y:'y' }, { x:'x', y:'y' }];

let result = A.map(({y,...rest})=> ({...rest,v:y}));

console.log(result);