Understand JavaScript's Map Method

Hello friends, In this article we will learn what is JavaScript Map() Function ? moreover, How can we use JavaScript Map() function ?

map function is used with an array. It applies function pass as an argument, to each and every element of array like iteration (looping).

In simple words, it is an iteration, which apply functionality on each of elements of array.

syntax :

let newArry = oldArry.map((val, index, arry) => { // return element to new Array });

oldArry : Array on which, functionality apply.

index : current element index (position in array)

arry : The origional array.

newArry : Return new array after functionality applied.

var old = [11,12,23,45,67]; var nw = old.map((e,i,a)=>e); nw;

OUTPUT: [11,12,23,45,67]

var old = [11,12,23,45,67]; var nw = old.map((e,i,a)=>i); nw;

OUTPUT: [0,1,2,3,4]

var old = [11,12,23,45,67]; var nw = old.map((e,i,a)=>a); nw;

OUTPUT: [Array[5],Array[5],Array[5],Array[5],Array[5]]

To understand map function, first create a simple program of array, which will returns square of each element of array.

var n = []; var a = [1,2,3,4,5]; for(var c=0;c<a.length;c++){ n.push(a[c]*a[c]); } console.log(n);

OUTPUT: [1,4,9,14,25]

Now let do it with function.

var arr = [1,2,3,4,5]; var Square = function(a){ var n = []; for(var c=0;c<a.length;c++){ n.push(a[c]*a[c]); } return n; } console.log(Square(arr));

Finally we will use JavaScript map function with our custom function Square();

We will create a function which Square the given number.

var Square = function(n){ return n*n; }

We will define an array and apply Square function to each element of array using JavaScript map function.

var arr = [1,2,3,4,5]; arr.map(Square);

Complete program will look like as follows.

var arr = [1,2,3,4,5]; var Square = function(n){ return n*n; } arr.map(Square);

OUTPUT (5) [1, 4, 9, 16, 25]

If you have any query or question or topic on which, we might have to write an article for your interest or any kind of suggestion regarding this post, Just feel free to write us, by hit add comment button below or contact via Contact Us form.


Your feedback and suggestions will be highly appreciated. Also try to leave comments from your valid verified email account, so that we can respond you quickly.

 
 

{{c.Content}}

Comment By: {{c.Author}}  On:   {{c.CreatedDate|date:'dd/MM/yyyy'}} / Reply


Categories