Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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;
};

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.

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

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);

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

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]

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

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]

Map takes all objects in a list and allows you to apply a function to it .

myArray = [1,2,3]
mappedArray = [];
    mappedArray = 
         myArray.map(function(currentValue){
         return currentValue *= 2;
       })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top