39

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]]
bwbrowning
  • 6,200
  • 7
  • 31
  • 36

6 Answers6

44

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));
Radosław Miernik
  • 4,004
  • 8
  • 33
  • 36
18

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 ));
TbWill4321
  • 8,626
  • 3
  • 27
  • 25
8

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

array.map(([ a, b ]) => [ a*2, b*2 ]);
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
3
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]]
Dharman
  • 30,962
  • 25
  • 85
  • 135
2

The simple way to do that at ES5:

[].concat(...this.array1.map(ap => ap.subArray))
Victor Zamanian
  • 3,100
  • 24
  • 31
Pedro Braz
  • 29
  • 3
-1

It can be a kind of entangle:

var Coef = Array.apply(null, Array(3)).map(function(){return
Array.apply(null, Array(4)).map(function(){return 0})})

Nevertheless, it can be useful if you want to initialize an array in Gas

Unheilig
  • 16,196
  • 193
  • 68
  • 98