How to manipulate the reduction function in crossfilter to create a certain array / object structure?

advertisements

I'm using crossfilter and am looking for a certain output after the reduce function:

var ndx = crossfilter(data);
var alDim = ndx.dimension(function(d) { return d.al_code_unique; });
var seatsPaxAirline = alDim.group().reduce(
            function(a, d) {
                a.seats += d.seats;
                a.pax += d.pax;
                return a;
            },
            function(a, d) {
                a.seats -= d.seats;
                a.pax -= d.pax;
                return a;
            },
            function() {
                return  {seats:0, pax:0 }; }
            ).top(100);

seatsPaxAirline is now an array of objects like this:

[
{key: "5Y", value: {pax: 60, seats: 100}},
{key: "4Y", value: {pax: 50, seats: 90}},
{key: "3Y", value: {pax: 40, seats: 80}}
]

But I do need the following output from the crossfilter reduce function:

[
 {key: "5Y", value: [ {name: "pax", value: 60}, {name: "seats", value: 100}},
 {key: "4Y", value: [ {name: "pax", value: 50}, {name: "seats", value: 90}},
 {key: "3Y", value: [ {name: "pax", value: 40}, {name: "seats", value: 80}},
]

I feel it's just a question of changing the reduce function in a certain manner but unfortunately I have no clue. Could someone help me on this? Thanks in advance!


As far as I understand the question, you need to change your reduce function like so:

var seatsPaxAirline = alDim.group().reduce(
            function(a, d) {
                a[0].value += d.seats;
                a[1].value += d.pax;
                return a;
            },
            function(a, d) {
                a[0].value -= d.seats;
                a[1].value -= d.pax;
                return a;
            },
            function() {
                return  [{name: 'seats', value: 0}, {name: 'pax', value: 0}]; }
            ).top(100);

The key is in how you set up the reduceInitial function, as that will determine the data structure of your 'a' object that gets passed through the reduce.