Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an array of arrays

Is there a method in lodash to map over an array of arrays

I would like to do something like this so that it keeps the structure of the array.

def double(x) { return x*2 }

_([[1,2],[3,4]]).somemethod(double) == [[2,4],[6,8]]
like image 524
bwbrowning Avatar asked Feb 10 '16 20:02

bwbrowning


People also ask

How do you map an array of arrays?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

How do I map multiple arrays?

To map multiple arrays with JavaScript, we can use the map method. to define the zip function that calls a1. map to combine the entries from a1 and a2 with index i into one entry. Then we call zip with arr1 and arr2 to zip them into one array.


Video Answer


4 Answers

Just _.map it twice:

var array = [[1, 2], [3, 4]];
var doubledArray = _.map(array, function (nested) {
    return _.map(nested, function (element) {
        return element * 2;
    });
});

Or without lodash:

var doubledArray = array.map(function (nested) {
    return nested.map(function (element) {
        return element * 2;
    });
});

Furthermore, consider using es6 arrow functions:

var doubledArray = array.map(nested => nested.map(element => element * 2));
like image 171
Radosław Miernik Avatar answered Oct 01 '22 16:10

Radosław Miernik


You can make your code much cleaner with ES2015 arrow functions:

var array = [[1, 2], [3, 4]];
var double = x => x * 2;
var doubledArray = _.map( array, subarray => _.map( subarray, double ));

Using vanilla JS:

var array = [[1, 2], [3, 4]];
var double = x => x * 2;
var doubledArray = array.map( subarray => subarray.map( double ));
like image 42
TbWill4321 Avatar answered Oct 01 '22 16:10

TbWill4321


It's much more elegant to use the es6 destructuring syntax within your map statement:

array.map(([ a, b ]) => [ a*2, b*2 ]);
like image 7
Lord Elrond Avatar answered Oct 01 '22 17:10

Lord Elrond


const deepMap=(input,callback)=>input.map(entry=>entry.map?deepMap(entry,callback):callback(entry))

//test 

deepMap([1,2,3,[1,2]],x=>x*2) // [1,4,9,[1,4]]
like image 2
user12160378 Avatar answered Oct 01 '22 16:10

user12160378