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? 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.
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):
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()
The
forEach()
method executes a provided function once per array element.
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>');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.