owenmelbz
owenmelbz

Reputation: 6584

Chunking Arrays by Condition Javascript

I'm trying to group some JSON data into pairs, for a slider, but we've got a layout rule as below

Portrait | Portrait
Landscape
Portrait | Portrait
Portrait | Portrait
Landscape
Landscape

So in the gallery, 2 portrait images can be next to each other, however landscape images use a view of their own.

The data I've got follows this basic setup

var photos = [
    {
        "id": "1",
        "landscape": false
    },
    {
        "id": "2",
        "landscape": false
    },
    {
        "id": "3",
        "landscape": true
    },
    {
        "id": "4",
        "landscape": true
    },
    {
        "id": "5",
        "landscape": false
    },
    {
        "id": "6",
        "landscape": true
    },
    {
        "id": "7",
        "landscape": false
    },
    {
        "id": "8",
        "landscape": false
    },
    {
        "id": "9",
        "landscape": false
    },
    {
        "id": "10",
        "landscape": false
    },
    {
        "id": "11",
        "landscape": false
    },
    {
        "id": "12",
        "landscape": true
    },
    {
        "id": "13",
        "landscape": true
    },
    {
        "id": "14",
        "landscape": false
    },
    {
        "id": "15",
        "landscape": true
    }
];

However I need to format it in a similar structure to below - trying to keep the original order of the data as intact as possible.

var views = [
    [{id:"1", landscape: false},{id:"2", landscape: false}],
    [{id:"3", landscape: false},{id:"4", landscape: false}],
    [{id:"5", landscape: true}],
    [{id:"6", landscape: false},{id:"7", landscape: false}],
    [{id:"7", landscape: true}]
]; //etc etc

We don't have access to jQuery, but have the full _underscore.js library to hand and of course native javascript.

Could somebody please shed some light on how this would be possible?

Many thanks

Upvotes: 0

Views: 349

Answers (1)

I would try something along this:

var portraits = chunk(photos.filter(function(v) {
    return v.landscape;
}), 2);
var landscapes = photos.filter(function(v) {
    return !v.landscape;
}).map(function(v) {
    return [v];
});
var rule = [0, 1, 0, 0, 1, 1];
var result = pick(landscapes, portraits, rule);

console.log(result);

function pick(a, b, rules) {
    a = _.clone(a);
    b = _.clone(b);

    var ret = [];
    var i, rule, len;

    for (i = 0, len = a.length + b.length; i < len; i++) {
        rule = rules[i % rules.length];

        ret.push(rule ? a.pop() : b.pop());
    }

    return ret.filter(_.identity);
}

function chunk(arr, len) {
    return _.chain(arr).groupBy(function(n, i) {
        return Math.floor(i / len);
    }).pairs().pluck(1).value();
}

Upvotes: 1

Related Questions