Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- 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" }];
- 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 }];
- var k = Object.keys;
- var items = MyArrayDefinition.reduce(function (o, v) {
- return o[v.item] = v, o;
- }, {});
- var shops = myArray.reduce(function (o, v, i, s) {
- return s = v[k(v).find(function (k) {
- return k;
- })], s = o[s] || (o[s] = {
- fruit: 0,
- vegetable: 0
- }), k(v).forEach(function (k) {
- return k.includes('item') && (s[(i = items[v[k]]).group] += i.score);
- }), o;
- }, {});
- // Helper function that calculates percentage
- function percentage(amount, total) {
- if (total === 0) {
- // added check for 0 divisor
- return "0%";
- }
- return amount / total * 100 + "%";
- }
- var result = k(shops).map(function (k, i) {
- var total = Object.values(shops[k]).reduce(function (a, b) {
- return a + b;
- }) | 0; // added check if number else 0
- var fruit = shops[k].fruit | 0; // added check if number else 0
- var veg = shops[k].vegetable | 0; // added check if number else 0
- return {
- id: i + 1,
- shop: k,
- fruit: fruit,
- vegetable: veg,
- total: total,
- fruitPercentage: percentage(fruit, total),
- vegetablePercentage: percentage(veg, total)
- };
- });
- console.log(JSON.stringify(result, null, 2));
- /** result from console.log()
- *
- [
- {
- "id": 1,
- "shop": "shop1",
- "fruit": 2,
- "vegetable": 2,
- "total": 4,
- "fruitPercentage": "50%",
- "vegetablePercentage": "50%"
- },
- {
- "id": 2,
- "shop": "shop2",
- "fruit": 2,
- "vegetable": 0,
- "total": 2,
- "fruitPercentage": "100%",
- "vegetablePercentage": "0%"
- }
- ]
- * */
Add Comment
Please, Sign In to add comment