Javascript Array Callback Functions Part 2 - Map Method
##MAP METHOD '.map()': Map creates a new array with the results of calling a callback just like .forEach() on every element in the array. However, Map is simply used to create a new array from an existing array.
SYNTAX:
Using anynomous function statement
arr.map(function (parameter) {
return parameter;
})
Using anynomous arrow function
arr.map( parameter => {
return parameter
})
EXAMPLE 1: Returning array elements in CAPS in a new array using .map() method.
//create a new array
const namesOfTechGiants = ['samson', 'goddy', 'Edidiong', 'asikpo', 'seun', 'daramola'];
const namesInCaps = namesOfTechGiants.map(function(names) {
return names.toUpperCase();
})
//OUTPUT
console.log(namesOfTechGiants);
'samson', 'goddy', 'Edidiong', 'asikpo', 'seun', 'daramola'
//The original values are still unchanged but have been mapped to a new array called 'namesInCaps'
//returning the values of the new array
console.log(namesInCaps);
'SAMSON', 'GODDY', 'EDIDIONG', 'ASKIPO', 'SEUN', 'DARAMOLA'
//.toUpperCase() is a method in Javascript that converts strings to capital letter
EXAMPLE 2: Create a new array of numbers that will return an object of 'isEven: true or false'
create a variable called numbers and initialize it to an array of numbers.
const numbers = [3, 4, 6, 7];
create a map method and initialize to a variable called numObjects
const numObjects = numbers.map(function(nums) {
return {
value: nums,
isEven: nums % 2 === 0 //isEven returns a boolean expression.
}
})
console.log(numObjects)
OUTPUT - The output is an array of objects and each object have a value and isEven either true or false.
0: {value: 3, isEven: false}
1: {value: 4, isEven: true}
2: {value: 6, isEven: true}
3: {value: 7, isEven: false}
EXAMPLE 3: Let's see how map method works on objects using the same object we created in our last episode.
const books = [{
title: 'Gods are not to blame',
author: 'Ola Rotimi',
},
{
title: 'Creating impressive proposals in Open Source Programs',
author: 'Edidiong Asikpo',
},
{
title: 'She inspires',
author: 'Bolaji Ayodeji'
},
{
title: 'javascript Grammer',
author: 'javascript Teacher',
}
];
const titles = books.map(function (book) {
return book.title
});
console.log(titles)
// OUTPUT
['Gods are not to blame', 'Creating impressive proposals in Open Source Programs', 'She inspires', 'javascript grammer']
// we have successfuly extracted the object titles we need using .map() without changing the original array
Like and share if you find this article useful.