Sometimes, we face a very common but very confusing situation where we have to think more deeply into it.

let’s say we have 2000 objects in an Array. Now we have to distribute all objects into n groups where n is integer digit. let’s say, 8 groups.

var allObjects = [{“id”:1}, {“id”:2}, {“id”:3}, {“id”:4}, {“id”:5}, …………,{“id”:2000}];

Now We need to group into 8 groups.

var grouped = [[{“id”:1}, {“id”:2}, {“id”:3}], [{“id”:1}, {“id”:2}, {“id”:3}].....]

Let’s get dirty hands into code. 😀

function createChunked(arr, chunkSize) {
    var onjects = [],
        i = 0,
        lmt = chunkSize;

    for (; i < arr.length; i += chunkSize) {

        if (lmt == (chunkSize * 8)) {
            lmt = lmt + arr.length - (chunkSize * 8);
        }
        if (lmt <= arr.length) {
            var tmpArray = arr.slice(i, lmt);
            onjects.push(tmpArray);
            lmt = lmt + chunkSize;
        }
    }
    return onjects;
}

var totalObj = allObjects.length;
var count = parseInt(totalObj / 8); // n=8
var grouped = createChunked(allObjects, count);
console.log(grouped);    

Happy Coding…!!! 🙂

Spread the love
Last modified: February 28, 2019

Comments

Write a Reply or Comment

Your email address will not be published.