Guest User

Untitled

a guest
Jun 22nd, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. "use strict";
  2.  
  3. var myArray = [{ "shop": "shop1", "item1": "my apple 1", "item2": "my carrot 1" }, { "shop": "shop1", "item1": "my apple 1", "item2": "my carrot 1" }, { "shop": "shop2", "item1": "my apple 0", "item2": "my carrot 0" }, { "shop": "shop2", "item1": "my apple 0", "item2": "my carrot 1" }];
  4. var MyArrayDefinition = [{ "item": "my apple 0", "color": "red", "group": "fruit", "score": 0 }, { "item": "my carrot 1", "color": "orange", "group": "vegetable", "score": null }, { "item": "my apple 1", "color": "red", "group": "fruit", "score": 1 }, { "item": "my carrot 0", "color": "orange", "group": "vegetable", "score": 0 }];
  5.  
  6. var k = Object.keys;
  7. var items = MyArrayDefinition.reduce(function (o, v) {
  8. return o[v.item] = v, o;
  9. }, {});
  10.  
  11. var shops = myArray.reduce(function (o, v, i, s) {
  12. return s = v[k(v).find(function (k) {
  13. return k;
  14. })], s = o[s] || (o[s] = {
  15. fruit: 0,
  16. vegetable: 0
  17. }), k(v).forEach(function (k) {
  18. return k.includes('item') && (s[(i = items[v[k]]).group] += i.score);
  19. }), o;
  20. }, {});
  21.  
  22. // Helper function that calculates percentage
  23. function percentage(amount, total) {
  24. if (total === 0) {
  25. // added check for 0 divisor
  26. return "0%";
  27. }
  28. return amount / total * 100 + "%";
  29. }
  30.  
  31. var result = k(shops).map(function (k, i) {
  32. var total = Object.values(shops[k]).reduce(function (a, b) {
  33. return a + b;
  34. }) | 0; // added check if number else 0
  35. var fruit = shops[k].fruit | 0; // added check if number else 0
  36. var veg = shops[k].vegetable | 0; // added check if number else 0
  37. return {
  38. id: i + 1,
  39. shop: k,
  40. fruit: fruit,
  41. vegetable: veg,
  42. total: total,
  43. fruitPercentage: percentage(fruit, total),
  44. vegetablePercentage: percentage(veg, total)
  45. };
  46. });
  47.  
  48. console.log(JSON.stringify(result, null, 2));
  49.  
  50. /** result from console.log()
  51. *
  52. [
  53. {
  54. "id": 1,
  55. "shop": "shop1",
  56. "fruit": 2,
  57. "vegetable": 2,
  58. "total": 4,
  59. "fruitPercentage": "50%",
  60. "vegetablePercentage": "50%"
  61. },
  62. {
  63. "id": 2,
  64. "shop": "shop2",
  65. "fruit": 2,
  66. "vegetable": 0,
  67. "total": 2,
  68. "fruitPercentage": "100%",
  69. "vegetablePercentage": "0%"
  70. }
  71. ]
  72. * */
Add Comment
Please, Sign In to add comment