Map an array of arrays

后端 未结 6 1774
太阳男子
太阳男子 2021-02-07 02:17

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         


        
6条回答
  •  无人共我
    2021-02-07 02:38

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

提交回复
热议问题