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

const numbers = [0,1,2,3];

console.log(numbers.map((number) => {
  return number;
}));

Example 3: map javascript

function map(collection, action) {
  let result = [];
  if (Array.isArray(collection)) {
    for (let i = 0; i < collection.length; i++) {
      result.push(action(collection[i], i, collection));
    }
  }
  else {
    for (let key in collection) {
      result.push(action(collection[key], key, collection));
    }
  } return result;
}