The array property: .map()

The array property: .map()
0

#1

var oldArray = [1, 2, 3];
var timesFour = oldArray.map(function(val){
return val * 4;
});
console.log(timesFour); // returns [4, 8, 12]
console.log(oldArray); // returns [1, 2, 3]

In our example the callback only uses the value of the array element (the val argument) but your callback can also include arguments for the index and array being acted on.

I don’t quite understand the second part of the passage where it talks about “arguments for the index and array being acted on”. Can someone explain that with some examples? Thank you!


#2

Take a look at the map documentation first. The Parameters section describes the 3 arguments which can be used. For an example of using both the currentValue argument and the index, see below.

var oldArray = [1, 2, 3, 4];
var multByIndex = oldArray.map(function(val, idx){
  return val * idx; // multiples each element by it's index
});
console.log(multByIndex ); // returns [0, 2, 6, 12]
console.log(oldArray); // returns [1, 2, 3, 4]

#3

oh!, its new knowledge for me thankyou
what about 3rd argument?