admin管理员组

文章数量:1390192

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"
    }
    }     
    ]

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"
    }
    }     
    ]
Share Improve this question edited Feb 6, 2015 at 6:41 gregdevs asked Feb 6, 2015 at 6:36 gregdevsgregdevs 7132 gold badges11 silver badges38 bronze badges 3
  • 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 Commented Feb 6, 2015 at 6:39
  • @NomanUrRehman sure. for every 4 I would output some markup under a parent div. probably in a ul. thanks. – gregdevs Commented Feb 6, 2015 at 6:40
  • Here is a good reference stackoverflow./a/10167931/3928341 – nem035 Commented Feb 6, 2015 at 6:43
Add a ment  | 

4 Answers 4

Reset to default 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/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/jfriend00/g95umf40/

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/984ru5dL/

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 e up with something more clever... :-)

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.

本文标签: loop through an array and retrieve groups of 5 objectsjavascriptStack Overflow