Friday 15 February 2013

Best way to summarize data for an array of objects using javascript and lodash -



Best way to summarize data for an array of objects using javascript and lodash -

i have array of objects , looking best efficient way grouping , summarize data. have couple hundred lines of codes , lots of 'for each' statements involved , know there lot easier way can't quite working.

here little sample of data. given info set might have several hundred products. each product has 5 stars , star can assigned 1 of 3 values (earned, not earned, or in progess). goal see summary of how many of each value assigned each star.

[{ product: "a" star1: "not earned" star2: "in progress" star3: "earned" star4: "not earned" star5: "in progress" },{ product: "b" star1: "in progress" star2: "not earned" star3: "in progress" star4: "earned" star5: "earned" }]

in end see result this: realize formating of objects , arrays off bit 1 more part of reason why i'm asking help. i'm using javascript , lodash.

results= [{ star1:{ in progress: 50, not earned: 32, earned: 1 },{ star2:{ in progress: 10 not earned: 14, earned: 11 },{ star3:{ in progress: 45, not earned: 25, earned: 19 }]

here 1 way it, not fastest, works, doesn't produce temp vars, it's not hard-coded info other single array var name (r), doesn't need library run (expect in dino browsers) , it's "simple":

var r=[{ product: "a", star1: "not earned", star2: "in progress", star3: "earned", star4: "not earned", star5: "earned" },{ product: "b", star1: "in progress", star2: "not earned", star3: "in progress", star4: "earned", star5: "earned" },,{ product: "c", star1: "in progress", star2: "not earned", star3: "not earned", star4: "earned", star5: "in progress" }]; var sums={}; // count holder object.keys(r[0]).foreach(function(k){ //for each key in info of sinlge info object this[k]=r.map(function(o){ homecoming o[k] }) // pluck values .map(function(w){ if(this[w]){this[w]++;}else{this[w]=1;} //count values using object homecoming this; },{}).pop(); // take 1 of count object copies (poor-man's cut down w/this) }, sums); // view result: json.stringify(sums, null, "\t") /* == { "product": { "a": 1, "b": 1, "c": 1 }, "star1": { "not earned": 1, "in progress": 2 }, "star2": { "in progress": 1, "not earned": 2 }, "star3": { "earned": 1, "in progress": 1, "not earned": 1 }, "star4": { "not earned": 1, "earned": 2 }, "star5": { "earned": 2, "in progress": 1 } */

the basic thought pluck values under each key, count values. two-pass solution might little slower hard-coded single-purpose routine , eliminates need hand-coded cut down function.

you can default in zeros if needed, wasn't sure if 2 illustration objects contained possible values set contains...

javascript arrays angularjs object lodash

No comments:

Post a Comment