Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS data manipulation

I have a data like this: (The real record has far more than this)

year    type    quantity
2011    A       1000
2012    B       1000
2012    C       1000
2012    A       1000
2015    A       1000

JSON:

[{year:2011, type:A, quantity:1000},...]

and i want to have the result like this: (I want every year and every type has a record there)

year    type    quantity
2011    A       1000
2011    B       -
2011    C       -
2012    A       1000
2012    B       1000
2012    C       1000
2015    A       1000
2015    B       -
2015    C       -

Is there any good way to do this? underscore solution is also welcomed!

like image 973
huan feng Avatar asked Dec 06 '25 03:12

huan feng


2 Answers

Vanilla JS, includes final sort

var yrs = [], types = [], tmp={};

data.forEach(function(item){
     // create arrays of years and types
     if(yrs.indexOf(item.yr) === -1){
        yrs.push(item.yr);
    }
    if(types.indexOf(item.type) === -1){
        types.push(item.type);
    }
    // temp object used in next step to look for holes
    tmp[item.yr + item.type] = true;
});

yrs.forEach(function(yr){
    types.forEach(function(type){
        // fill in holes
        if(!tmp.hasOwnProperty(yr+type)){
           data.push({yr: yr, type: type, qty: 0});
         }
    })
});

data.sort(function(a,b){
    return b.yr === a.yr ? a.type > b.type : +a.yr - +b.yr
});

DEMO

like image 85
charlietfl Avatar answered Dec 07 '25 21:12

charlietfl


Hope this will work with underscore:

var source = [{year: "2011", type: "A",...} ...];
var years = _.uniq(_.map(source , function(item){
    return item.year;
}))

var types = _.uniq(_.map(source , function(item){
    return item.type;
}))

var result = [];
_.each(years, function(yearItem){
    _.each(types, function(typeItem){
      var resultItem = _.find(source, function(item){
            return item.year === yearItem && item.type === typeItem;
        })
       if(undefined === resultItem){
             resultItem = {
               year: yearItem,
               type: typeItem,
               quantity: "-"
             };{}
       } 
           result.push(resultItem);


    })
})
like image 44
Miyuru Ratnayake Avatar answered Dec 07 '25 22:12

Miyuru Ratnayake