-6

How to group by based on two json key which is f and b My json array

var json=[
    {   s:'s',  f:1,  b:1,  q:2   },
    {   s:'s',  f:1,  b:1,  q:3   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2    },
    {   s:'s',  f:1,  b:0, q:2    },
    {   s:'s',  f:0,  b:0,  q:2    },
    {   s:'s',  f:0,  b:0, q:2    },

];

Expected Output

 var op=[
    {   s:'s',  f:1,  b:1,  q:5   },
    {   s:'s',  f:2,  b:1,  q:4   },
    {   s:'s',  f:1,  b:2,  q:4   },
    {   s:'s',  f:0,  b:1,  q:4   },
    {   s:'s',  f:1,  b:0,  q:4   },
    {   s:'s',  f:0,  b:0,  q:4   },

];

  • Can you write out a Pseudocode example to explain since you have not posted a code attempt? Your example above is not clear on how exactly you want to group the object. – Spangle Mar 11 '19 at 07:10
  • 1
    Possible duplicate of [Removing elements from an array of objects based on duplicate values of multiple keys](https://stackoverflow.com/questions/38046236/removing-elements-from-an-array-of-objects-based-on-duplicate-values-of-multiple) and [Remove duplicates from an array of objects in JavaScript](https://stackoverflow.com/questions/2218999) and [How to remove duplicates objects in array based on 2 properties?](https://stackoverflow.com/questions/46402325) – adiga Mar 11 '19 at 07:24

1 Answers1

0

var json=[
    {   s:'s',  f:1,  b:1,  q:2   },
    {   s:'s',  f:1,  b:1,  q:3   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:2,  b:1,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:1,  b:2,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:0,  b:1,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2   },
    {   s:'s',  f:1,  b:0,  q:2   },
    {   s:'s',  f:0,  b:0,  q:2   },
    {   s:'s',  f:0,  b:0,  q:2   },
];

var result = Object.values(json.reduce((list, cur) => {
    if(list[cur.f + ',' + cur.b])
        list[cur.f + ',' + cur.b].q += cur.q
    else
        list[cur.f + ',' + cur.b] = Object.assign({}, cur)
    return list
}, {}))
console.log(result)
wang
  • 1,660
  • 9
  • 20