Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain this particular use of the method map?

I saw this as a solution for a codewars challenge where you need to reverse an array without using the reverse method and using just 30 bits spare:

reverse=a=>[...a].map(a.pop,a)

Now the way I know to use map is something like this:

array.map(item => somethingelse)

So I dont really understand how map is used in that case, could somebody explain please?

like image 634
Talmacel Marian Silviu Avatar asked Sep 04 '20 00:09

Talmacel Marian Silviu


People also ask

For which purpose the map method is used?

map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array's elements. The Array.

Is map method destructive?

map() is a non-destructive method. However, the callback function you pass to . map() can make it destructive.

How does JavaScript map work?

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.


1 Answers

The first parameter .map accepts is the callback to run on every iteration.

array.map(item => somethingelse)

is equivalent to

const callback = item => somethingelse;
array.map(callback);

The second parameter .map accepts is the this value to use while running the callback. To illustrate:

const obj = {};
const arr = [0, 1, 2];
const arr2 = arr.map(
  function() { console.log(this === obj) },
  obj
);

It's usually pretty weird to reference this inside a .map, but it's possible, and by passing a second argument, you can determine what it refers to.

Array.prototype.pop requires a calling context - a this value - to know which array you're trying to pop items from, so in the original code:

reverse=a=>[...a].map(a.pop,a)

a must be passed as a second argument for the .map to work.

a.pop is equivalent to Array.prototype.map here, because it's passed as a callback:

// Equivalent code:
reverse=a=>[...a].map(Array.prototype.pop, a);

The [...a].map( part is being used as a shortcut to invoke .pop() n times, where n is the length of the original array. Each item returned results in a new item in the new array - last item in the original array is popped first and put into the first position in the new array, and so on.

like image 146
CertainPerformance Avatar answered Oct 25 '22 20:10

CertainPerformance