[英]Javascript create a two dimensional array from one dimensional array using map
I have an array : 我有一个数组:
var a = [{name : 'foo1'},{name : 'foo2'},{name : 'foo3'},{name : 'foo4'},{name : 'foo5'}]
How can I output and array from original array like the one below? 我如何从原始数组输出和数组,如下所示?
[[{name : 'foo1'},{name : 'foo2'}],[{name : 'foo3'},{name : 'foo4'}],[{name : 'foo5'}]]
using the Array.prototype.map function? 使用Array.prototype.map函数? thanks. 谢谢。
Solution using map and filter: 使用地图和过滤器的解决方案:
var a = [{name : 'foo1'},{name : 'foo2'},{name : 'foo3'},{name : 'foo4'},{name : 'foo5'}];
var b = a.map(function(val, index, arr){
if (index % 2 === 0){
var pair = [val];
if (arr.length > index+1){
pair.push(arr[index+1]);
}
return pair;
} else {
return null;
}
}).filter(function(val){ return val; });
It maps even items to arrays of 2, and odd items to null, then the filter gets rid of the nulls. 它将偶数项映射到2的数组,将奇数项映射到null,然后过滤器将摆脱null。
If you really want to use map
, then create a range from 0
to ceil(length/2)
and call map
to take 2 elements for each (or 1 or 2 for the last one): 如果您确实想使用map
,则创建一个从0
到ceil(length/2)
的范围,并调用map
以每个元素取2个元素(或最后一个元素取1或2个元素):
Array.apply(null, Array(Math.ceil(a.length / 2))).map(function (_, i) {return i;}).map(
function(k) {
var item = [a[k*2]];
if (a.length - 1 >= k*2+1)
item.push(a[k*2+1]);
return item;
}
);
A solution with Array#forEach()
Array#forEach()
解决方案
The
forEach()
method executes a provided function once per array element.forEach()
方法每个数组元素执行一次提供的函数。
var a = [{ name: 'foo1' }, { name: 'foo2' }, { name: 'foo3' }, { name: 'foo4' }, { name: 'foo5' }], grouped = function (array) { var r = []; array.forEach(function (a, i) { if (i % 2) { r[r.length - 1].push(a); } else { r.push([a]); } }, []); return r; }(a); document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.