Javascript Array map() for Junior
What is map() function?
Map is a collection of elements where each element is stored as a Key, value pair. The map() method is used to apply a function on every element in an array. A new array is then returned.
Array.map function has following signature:
arr.map(function callback(currentValue[, index[, array]])
Example:
const number=[1,2,3,4,5];
let newArr = number.map((val, index, arr) => {
// return element to new Array
});
newArr
— the new array that is returnednumber
— the array to run the map function onval
— the current value being processedindex
— the current index of the value being processedarr
— the original array
map() Vs for loop
Map works same as the for loop the only difference is that map() returns a new array where as for loop change the exiting array or collect elements in a new array.
Example:
const numbers = [1, 2, 3, 4];
for(let i = 0; i < number.length; i++) {
numbers[i] = numbers[i] + 5;
}
console.log(numbers);
// [6, 7, 8, 9]
Example of map() function
const numbers = [1, 2, 3, 4];
const list = numbers.map(function(num) {
return num + 5;
});
console.log(list);
// [6, 7, 8, 9]
Example 1: Convert array of object to string using map()
Return list of student names from an array of objects representing student information.
const students = [
{ id: 1, name: 'Jason', age: 10},
{ id: 2, name: 'Peter', age: 8},
{ id: 3, name: 'Sara', age: 9}
];
const studentNames = students.map(student => student.name);
console.log(studentNames);
// ['Jason', 'Peter', 'Sara']
Example 2: Create array of length of strings in an array using map()
const names = ['John', 'Pat', 'Debby'];
const nameLengths = names
.map(n => n.length);
console.log(nameLengths);
// [4, 3, 5]
Example 3: Chaining of multiple map() functions in an array
const names = ['John', 'Pat', 'Debby'];
const nameLengths = names
.map(n => n.length) // Gives the length of a string
.map(n => n * n); // multiply's the length from the above map
console.log(nameLengths);
// [16, 9, 25]