-4

I know I can pass a function that looks like this to the array method .map():

var cities = ["rome", "san francisco", "tokyo"];

var cityLen = cities.map(x => x.length);

console.log(cityLen)

// OUTPUT: [4, 13, 5]

I'm passing a single parameter (x) to the anonymous function in map where x gets progressively assigned to each of the elements of cities.

In the code below have been passed two parameters (d and i) to the anonymous function.

function numberRange (start, end) {
  return new Array(end - start).fill().map((d, i) => i + start);
}

numberRange(10, 20)

// OUTPUT [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

What are the parameters d and i inside the anonymous function and how do they get assigned? How do multiple parameters functions work with .map()?

leonardofed
  • 936
  • 2
  • 9
  • 24

2 Answers2

2

As you can see on MDN, Array#map is called with three arguments:

  • The current value
  • The current index
  • The object on which it was called

So that map called is called with each value in the array and its index (and the array, but it doesn't declare a parameter for it).


Side note: You could avoid unnecessary multiple passes through the array (basically, combine the fill and map) with Array.from:

return Array.from({length: end - start}, (d, i) => i + start);

Array.from calls its callback with the current value and its index.

Example:

function numberRange (start, end) {
  return Array.from({length: end - start}, (d, i) => i + start);
}
console.log(numberRange(10, 20));

You could also avoid using i entirely by incrementing start:

return Array.from({length: end - start}, () => start++);

Example:

function numberRange (start, end) {
  return Array.from({length: end - start}, () => start++);
}
console.log(numberRange(10, 20));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    My bad. Didn't notice in the doc. Need some rest :) Didn't know array.from, looks a cleaner way to accomplish the same result. Thanks. – leonardofed Jun 27 '18 at 13:54
2

Beside the second parameter, which is ususally the index of the actual element of forEach, some, every, map, you could use Array.from, which generates an array out of an object with a length property and has a second parameter for a mapping function.

function numberRange (start, end) {
    return Array.from({ length: end - start}, (_, i) => i + start);
}

console.log(numberRange(10, 20));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392