Array Map in Javascript
Array Map can be used to create a new array by calling a function on each element on a another array using .map()
method. This is done declaratively alternate to the imperative approch using Array.push()
inside a loop.
Examples
1
2
3
4
5
6
7
const cities = [
{ name: 'Bangalore'},
{ name: 'Chennai'},
{ name: 'Kochi'},
{ name: 'Trivandrum'}
];
By using .map()
we can create a new array cityNames[]
declaratively
1
const cityNames = cities.map(city => cities.name)
The function which need to be called on the each element of the original array is passed as an argument to the map()