Given an array of numbers. Using the
map
method, extract the square
root of each array element and write
the result to a new array.
map method to iterate over an array in JavaScript
Given an array with strings. Using the
map
method, add the character
'!'
to the end of the value of
each array element.
Given an array with strings. Using the
map
method, reverse the
characters of each string.
Given the following array:
let arr = ['123', '456', '789'];
Using the map
method, transform
this array into the following:
let arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
Element key
The callback function can also take a second parameter - JavaScript will place the key of the array element into it.
Let's look at an example. Let's have an array like this:
let arr = ['a', 'b', 'c', 'd', 'e'];
Let's write at the end of each element its index number in the array:
let arr = ['a', 'b', 'c', 'd', 'e'];
let result = arr.map(function(elem, index) {
return elem + index;
});
console.log(result); // shows ['a0', 'b1', 'c2', 'd3', 'e4']
Given an array of numbers. Using the
map
method, write to each element
of the array the value of this element
multiplied by its index number in the array.
Iterating over multidimensional arrays
The map
method can also be used to
iterate over multidimensional arrays. Let,
for example, given an array like this:
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
Let's iterate over this array through
map
and output its elements to
the console:
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let result = arr.map(function(elem) {
console.log(elem);
});
As a result, console.log
will
output [1, 2, 3]
, then [4, 5, 6]
,
then [7, 8, 9]
.
As you can see, subarrays get into the
variable elem
. Let's now apply
the map
method to each subarray
and square each of its elements:
let arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let result = arr.map(function(elem) {
return elem.map(function(num) {
return num * num;
});
});
console.log(result);