What is the concept of Array.map?
Asked Answered
E

10

25

I am having problems understanding the concept of Array.map. I did go to Mozilla and Tutorials Point, but they provided very limited info regarding this.

This is how I am using Array.map. It is a little complex (a bit of d3.js involved; just ignore it)

var mapCell = function (row) {
    return columns.map(function(column) {
        return { column : column, value : getColumnCell(row, column) }
    })
}
//getColumnCell is a function defined in my code
//columns is array defined at the top of my code

I do not understand exactly what this code is doing. I know its returning a new array and stuff but this part is a little tricky!

If you want to go through my code: http://jsfiddle.net/ddfsb/2/

I am using console to actually understand what's happening inside the code. Looking at the answers provided, I have clearly understood the concept of array.map. Now the only part remaining is parameters rows and columns, but there is a difference between row and rows, and column and columns in the fiddle provided

var rows//completely ok
var columns//completely ok
funcion(row)//here,source of row is unknown.getColumncell function utilizes this parameter further making it more critical
function(column)//source of column is unknown..getColumncell function utilizes this parameter further making it more critical
Earthshine answered 28/6, 2013 at 15:6 Comment(0)
C
26

Let's rewrite it a bit, and start working from inside out.

var mapCell = function (row) {
  return columns.map(
    function(column) {
      return { 
        column : column, 
        value : getColumnCell(row, column)
      }
    }
  )
}

The function(column) part is essentially a function that takes a column as a parameter, and returns a new object with two properties:

  • column, that is the original value of the parameter, and
  • value, that is the result of calling the getColumnCell function on the row (external variable) and column (parameter)

The columns.map() part calls the Array.map function, that takes an array and a function, and runs the function for every last item of it, and returns the results. i.e. if the input is the array [1, 2, 3, 4, 5] and the function is something like isEven, the result will be the array [false, true, false, true, false]. In your case, the input are the columns, and the output is a list of objects, each of which has a column and a value properties.

Lastly, the var mapCell = function (row) part declares that the variable mapCell will contain a function of one variable called row - and this is the same row that is used in the inner function.

In a single sentence, this line of code, declares a function that when run, will take a row and return values for all columns for that row.

Cavin answered 28/6, 2013 at 15:26 Comment(2)
can i know where is this column parameter and the row parameter coming from,the thing is i just dumped this code from a website without understanding and now i am suffering..Smiley
The assumption in this code is that the row parameter is passed to the function, that columns is a collection of things called column, and that there exists a function called getColumnCell that takes a row and a column as parameters. From this snippet only, it's impossible to say what they are or where those things come from.Cavin
S
4

map loops through your original array and calls the method for each value in the array. It collects the results of your function to create a new array with the results. You are "mapping" the array of values into a new array of mapped values. Your code is equivalent to:

var mapCell = function (row) {
    var result = [];
        for (var i = 0; i < columns.length; ++i) {
            var mappedValue = {
                column: columns[i], 
                value : getColumnCell(row, columns[i])
            };
            result.push(mappedValue);
        }
    return result;
};
Sethrida answered 28/6, 2013 at 15:19 Comment(0)
D
3

Understanding the map function is only part of the solution here, there is also the function mapCell. It takes one parameter row and it returns something like:

[ {
    "column": "parties",
    "value": [cell value]
}, {
    "column": "star-speak",
    "value": [cell value]
} ]

Where the cell value depends on the row and the column (parties, stars-speak etc.)

A map function applies a transformation to a value, and returns that transformed value.

A simple example:

function square(x) { return x * x; }

[ 2, 3, 4 ].map(square); // gives: [ 4, 9, 16 ]

Similarly:

[ "parties", "starspeak" ].map(function (column) {
    return {
        column: column,
        value: findTheValue(column)
    }
});

Now since that map is nested with a function that gets a row parameter. You can use it in the map function, to get:

function (row) {
    return [ "parties", "starspeak" ].map(function (column) {
        return {
            column: column,
            value: findTheValue(row, column)
        }
    });
}

And this gets pretty close to your code.

Documentary answered 28/6, 2013 at 15:21 Comment(3)
i dint understood the function(row) and .map(function (column){}.... these parameters inside the function causing me problem. where are these parameters coming fromSmiley
where are these parameter row and column coming from??Smiley
column are the elements of columns, so "parties", "starspeak" etc. row is passed in as an argument from elsewhere.Documentary
D
2

Map function goes through each element of an array in ascending order and invokes function f on all of them. It returns new array which is being computed after function is invoked on it.

Syntax:
array.map(f)

Example:

<!doctype html>
<html>
 <head>
 <script>
   var arr = [4,5,6];
   document.write(arr.map(function(x){return x*2;}));
 </script>
 </head>
</html>

Answer: 8,10,12

Daemon answered 23/9, 2015 at 10:19 Comment(0)
V
2

Summary

Array.map is a function which is located on Array.prototype.map. The function does the following:

  1. Creates a new array with the same amount of entries/elements.
  2. Executes a callback function, this function receives and current array element as an argument and returns the entry for the new array.
  3. Returns the newly created array.

Example:

Basic usage:

const array = [1, 2, 3, 4];

// receive each element of array then multiply it times two
// map returns a new array
const map = array.map(x => x * 2);

console.log(map);

The callback function also exposes an index and the original array:

const array = [1, 2, 3, 4];

// the callback function can also receive the index and the 
// original array on which map was called upon
const map = array.map((x, index, array) => {
  console.log(index);
  console.log(array);
  return x + index;
});

console.log(map);
Viki answered 29/10, 2018 at 18:7 Comment(0)
K
0

Probably most people coming here (like me) just want a basic array.map usage example:

myArray = [1,2,3]
mappedArray = [];

mappedArray = myArray.map(function(currentValue){
     return currentValue *= 2;
})

//myArray is still [1,2,3]
//mappedArray is now [2,4,6]

This is it at it's most basic. For additional parameers, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Ka answered 26/10, 2016 at 14:59 Comment(0)
M
0

IF you have an array of elements and you have to perform the same operation on the each element of the array that time you can use the javascript map function for array it helps to iterate throw the array then we can perform the operation of each element and return it.

let NumberArray = [1,2,3,4,5,6,7,8];

let UpdatedArray = NumberArray.map( (Num , index )=>{ 
                return Num*10;
            })

console.log(UpdatedArray);

//UpdatedArray ==> [10, 20, 30, 40, 50, 60, 70, 80]
Monkshood answered 31/7, 2019 at 11:47 Comment(0)
C
0

Javascript map() Syntax

arrayObj.map(callback[,context]);

arrayObj is a original array on which map() is invoked.

The map() takes 2 named arguments, First is a callback function and the second is a context object. callback function gets triggered on every element of an array.

In addition, callback function takes 3 arguments:

function callback(currentElement,index,array){

}

currentElement – This is a current elements of array which is passed to callback function

index – Index of the current element

array – complete array on which map() is applied

Out of these 3 elements, currentElement parameter is mandatory while the rest 2 parameters are optional.

However, map() does not change the original array, it creates a new array element which is generated by callback function.

You can read more on JavaScript map function

Chayachayote answered 11/10, 2020 at 13:3 Comment(0)
I
0

Array map() method returns a new array. It does not change the original array.

let array = arr.map((c, i, arr) => { //return element to new array });

here,

  • array is the new array that is returned.
  • arr is the original array on which the map method is called.
  • c is the current value that is being processed.
  • i is the index of current value.

For example:-

const originalArr = [4, 3, 2]; let newArr = originalArr.map((val) => val + val);

result:-

newArr: [8, 6, 4] originalArr: [4, 3, 2]

Inject answered 24/4, 2021 at 12:20 Comment(0)
C
0

in simple words you can perform operations on array using map

Examples 1.Array

let arr = ["sam","tom"]

console.log("Before map :",arr)
arr.map((d,i)=>{
    arr[i] = d+"yy"
})

  console.log("After map  :",arr)

Examples 2.Array Of Objects

// console.log(Date.now());

let arr = [
  {name:"sam",roll_no:10},
  {name:"tom",roll_no:12}
]
  
  console.log("Before map :",arr)
  
arr.map(d=>{
  if(d.name == "sam")
  {
      d.name = "sammy",
      d.roll_no=100
  }
})

  console.log("After map :",arr)
Cortico answered 29/7, 2022 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.