0

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.

Yvon Huynh
  • 453
  • 3
  • 16

3 Answers3

1

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.

Orr Siloni
  • 1,268
  • 10
  • 21
0

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;
  }
);
Leventix
  • 3,789
  • 1
  • 32
  • 41
  • First i have tested the three methods and they all work as expected thank you in advance. I chose the first one since I can only choose on answer. – Yvon Huynh Feb 25 '16 at 13:41
0

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392