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.
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:
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.
Array.map
is a function which is located on Array.prototype.map
. The function does the following:
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);