How can we group array object by properties. For example below I want to group the sample data by its oldStockBooks.name
(see expected result at the bottom)?
Been to these following links, but I can't apply it in my scenario stack-link-1, stack-link-2.
I have tried these code below, but it does not work as intended.
var counter = {};
oldStockBooks.forEach(function(obj) {
var key = JSON.stringify(obj)
counter[key] = (counter[key] || 0) + 1
});
Sample data:
const oldStockBooks = [
{
name: 'english book',
author: 'cupello',
version: 1,
//... more props here
},
{
name: 'biology book',
author: 'nagazumi',
version: 4,
},
{
name: 'english book',
author: 'cupello',
version: 2,
},
];
Expected result: display name
, author
, and total
props only. And total
props would be the number of duplication by book name.
const output = [
{
name: 'english book',
author: 'cupello',
total: 2,
},
{
name: 'biology book',
author: 'nagazumi',
total: 1,
},
];