Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Self-Referencing Map - Very Bizarre Result

While experimenting with some different methods for generating JavaScript arrays, I stumbled on a weird result. Using map to push an array of self-references (DEMO):

a=[1,1,1,1,1,1,1,1,1,1];
a=a.map(a.push,a);

I get the following result (in Chrome):

[13,16,19,22,25,28,31,34,37,40]

Can anyone explain why?

like image 329
mellamokb Avatar asked Jan 25 '13 05:01

mellamokb


People also ask

Does map return an array?

The map() method returns an entirely new array with transformed elements and the same amount of data. In the case of forEach() , even if it returns undefined , it will mutate the original array with the callback .

What is array and map?

Definition and Usagemap() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

How do I map an array in Javascript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

How do you make an array map?

To create an Array from Map, we can use map. entries() method. let newIterable = map. entries(map); //return iterable with [key,value] pairs let newArray = Array.


2 Answers

For each element in a, push is being called with that element, the index of that element, and the array being traversed. For each element in the array, then, we add these three additional elements. This accounts for the length increasing by three for each element in the original array. The result of push is the length of the array after the elements are added, thus the resulting array (from map) is an array holding the lengths of the a array after each push callback is completed.

See the documentation for map and push.

like image 182
tvanfosson Avatar answered Sep 21 '22 17:09

tvanfosson


It has something to do with the return value of push being the new length. Not sure why it incrementing by 3.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push

Returns
The new length property of the object upon which the method was called.

like image 45
gahooa Avatar answered Sep 18 '22 17:09

gahooa