function data_map() { var data = [ ['a','b', 1], ['c','d', 2], ['e','f', 3], ['g','h', 4] ] var newData = data.map(function(row){ return [row[0], ro
Function data_map()
var data = [
['a','b', 1],
['c','d', 2],
['e','f', 3],
['g','h', 4]
];
var newData = data.map(function(row){
return [row[0], row[2]];
});
The data_map()
function creates a new array, newData
, by mapping each element from the original array, data
. Each element in the data
array is itself an array of three elements. The first two elements are strings, and the third element is a number.
The Callback Function
The callback function used in the map()
method takes a single argument, row
, which represents the current element from the data
array being processed. The function then returns a new array containing only the first and third elements of the current row.
var newData = data.map(function(row){
return [row[0], row[2]];
});
Alternative Ways to Achieve the Same Result
Another way to achieve the same result is by using arrow function syntax instead of function declaration syntax. This would look like:
var newData = data.map((row) => [row[0], row[2]]);
Additionally, one could use destructuring assignment to directly extract the first and third elements of each row into a new array. This would look like:
var newData = data.map(([first, second, third]) => [first, third]);