Javascript 映射数组数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35325767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map an array of arrays
提问by bwbrowning
Is there a method in lodash to map over an array of arrays
lodash 中是否有一种方法可以映射数组数组
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]]
采纳答案by TbWill4321
You can make your code much cleaner with ES2015 arrow functions:
你可以使用 ES2015 箭头函数让你的代码更简洁:
var array = [[1, 2], [3, 4]];
var double = x => x * 2;
var doubledArray = _.map( array, subarray => _.map( subarray, double ));
Using vanilla JS:
使用香草JS:
var array = [[1, 2], [3, 4]];
var double = x => x * 2;
var doubledArray = array.map( subarray => subarray.map( double ));
回答by Rados?aw Miernik
Just _.map
it twice:
只是_.map
两次:
var array = [[1, 2], [3, 4]];
var doubledArray = _.map(array, function (nested) {
return _.map(nested, function (element) {
return element * 2;
});
});
Or without lodash
:
或者没有lodash
:
var doubledArray = array.map(function (nested) {
return nested.map(function (element) {
return element * 2;
});
});
Furthermore, consider using es6 arrow functions:
此外,考虑使用es6 箭头函数:
var doubledArray = array.map(nested => nested.map(element => element * 2));
回答by manguel1980
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
然而,如果你想在Gas 中初始化一个数组,它会很有用
回答by user12160378
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]]
回答by Pedro Braz
The simple way to do that at ES5:
在 ES5 中做到这一点的简单方法:
[].concat(...this.array1.map(ap => ap.subArray))
[].concat(...this.array1.map(ap => ap.subArray))