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.

4
  • no, because Array#map is one to one mapping. Commented Feb 25, 2016 at 12:39
  • Is there no special condition on your grouping? Jut simply group the first 2 element, then the next 2 etc Commented Feb 25, 2016 at 12:39
  • @ste2425 no special condition, just take the first two group them, take the next two then group them etc Commented Feb 25, 2016 at 12:42
  • Array.prototype.reduce will help you Commented Feb 25, 2016 at 12:50

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.