0

I have an array with some objects and simply want to loop through the array and output 4 at a time..I would place every 4 objects into a parent div tag and maybe a ul. Not exactly sure of the best approach. I'm sure there are a few ways and wanted to get some ideas or feedback in terms of cleanest approaches. Thanks.

var data = [
    {
    "parent":{
      "firstname": "firstname",
      "lastname": "lastname2"
    }
    },
    {
    "parent":{
      "firstname": "firstname2",
      "lastname": "lastname3"
    }
    },
    {
    "parent":{
      "firstname": "firstname",
      "lastname": "lastname2"
    }
    },
    {
    "parent":{
      "firstname": "firstname2",
      "lastname": "lastname3"
    }
    },
    {
    "parent":{
      "firstname": "firstname",
      "lastname": "lastname2"
    }
    },
    {
    "parent":{
      "firstname": "firstname2",
      "lastname": "lastname3"
    }
    },
    {
    "parent":{
      "firstname": "firstname",
      "lastname": "lastname2"
    }
    },
    {
    "parent":{
      "firstname": "firstname2",
      "lastname": "lastname3"
    }
    }     
    ]
gregdevs
  • 703
  • 2
  • 11
  • 37
  • 2
    Can you post more details about how you intend to treat the batch of 4 you get ? What will you do with them ? This will help suggest a solution. – Noman Ur Rehman Feb 06 '15 at 06:39
  • @NomanUrRehman sure. for every 4 I would output some markup under a parent div. probably in a ul. thanks. – gregdevs Feb 06 '15 at 06:40
  • Here is a good reference http://stackoverflow.com/a/10167931/3928341 – nem035 Feb 06 '15 at 06:43

4 Answers4

3

You can iterate and just keep track of how many are in the current group and start a new group when that group fills up. This code breaks the original array into an array of groups where each group has no more than the desired number in it. You can then use that array of groups to create whatever type of output you want:

function breakArrayIntoGroups(data, maxPerGroup) {
    var numInGroupProcessed = 0;
    var groups = [[]];
    for (var i = 0; i < data.length; i++) {
        groups[groups.length - 1].push(data[i]);
        ++numInGroupProcessed;
        if (numInGroupProcessed >= maxPerGroup && i !== (data.length - 1)) {
            groups.push([]);
            numInGroupProcessed = 0;
        }
    }
    return groups;
}

var groups = breakArrayIntoGroups(data, 5);

Working demo: http://jsfiddle.net/jfriend00/pas3czxn/


Here's an even simpler version that uses .slice() to copy maxPerGroup items at a time from the original array:

function breakArrayIntoGroups(data, maxPerGroup) {
    var groups = [];
    for (var index = 0; index < data.length; index += maxPerGroup) {
        groups.push(data.slice(index, index + maxPerGroup));
    }
    return groups;
}

var groups = breakArrayIntoGroups(data, 5);

Working demo: http://jsfiddle.net/jfriend00/g95umf40/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Cool, I figured looping and pushing every 4 into a new array might be the best way to go. – gregdevs Feb 06 '15 at 07:01
  • @gregthewebbandit - I turned the code into a more generic function and update the demo jsFiddle too. – jfriend00 Feb 06 '15 at 07:04
  • 1
    @gregthewebbandit - I added an even simpler and faster version. – jfriend00 Feb 06 '15 at 07:13
  • no doubt simpler, but the first version laid the blueprint with the for/if statement, was a bit more familiar to what i was thinking. and thanks for showcasing it as a function. pretty slick – gregdevs Feb 06 '15 at 07:20
  • 1
    @gregthewebbandit - The second version just says, get 5 items and put them in a group. Get the next 5 items and put them in a group and so on. It's how a person would actually do a task like this if you asked them to do something like this manually. The person would count items 1,2,3,4,5 then put these in a new group. Count items 1,2,3,4,5 and put them in a group and so on until the items were all gone. – jfriend00 Feb 06 '15 at 07:24
2

Allright, I'll play. A simple option would be to just iterate over the array and place 4 records, then add a break or whatever delimiter you want, then show the next 4. Keep doing this until you run out of array..

var start = 0;
var el = document.getElementById('insertHere');
while (start < data.length) {
    for (var i = start; i < start + 4; i++) {    
    el.innerHTML += data[i].parent.firstname + " - " + data[i].parent.lastname + "<br />";
    }
    el.innerHTML += "<br/><br/>"
    start += 4;
}

http://jsfiddle.net/984ru5dL/

Tarske
  • 163
  • 8
1

Something like this would work on your data, sorry - I used jQuery:

var grouperise = (function (g, a) {
    var groups = {};

    $.each(a, function (n, v) {
        var ng = Math.trunc(n/g);

        groups[ng] = groups[ng] || [];
        groups[ng].push(v);
    });

    var result = [];

    for (var index in groups) {
        result.push(groups[index]);
    }

    return result;
});

Usage:

var groupies = grouperise(5, data);

console.log(groupies);

No doubt someone will come up with something more clever... :-)

Paul
  • 1,502
  • 11
  • 19
0

You can simply loop over the array in batch of 4 like this:

for(i=0; i < array.length; i=i+4){
    i-1 // gives you fourth element in batch
    i-2 // gives you third element in batch
    i-3 // gives you second element in batch
    i-4 // gives you first element in batch
}

This will work well for array with length in multiples of 4 but if that is not the case, one extra check can take care of that too.

Noman Ur Rehman
  • 6,707
  • 3
  • 24
  • 39