A flat JSON array contains repetitive identifier
, categoryId
, and category
:
data: [
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Aunt Hattie's",
"price": "375"
},
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Back to Nature",
"price": "343"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mars Muffin (McVitie's)",
"price": "465"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "McVitie's",
"price": "251"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mr Kipling",
"price": "260"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mr Kipling Frosty Fancies",
"price": "210"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Amul",
"price": "474"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Borden",
"price": "184"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Broughton Foods Company",
"price": "43"
},
]
To calculate the total price for each category and add a new object at the end of each category with the identifier set as Total
along with the total value, you can use the following sorting function:
function compare(a,b) {
if (a.categoryId < b.categoryId)
return -1;
if (a.categoryId> b.categoryId)
return 1;
return 0;
}
data.sort(compare);
UPDATED OUTPUT FORMAT
The desired output format is as follows:
: [
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Aunt Hattie's",
"price": "110"
},
{
"identifier": "data",
"categoryId": "1",
"category": "Baked goods",
"product": "Back to Nature",
"price": "344"
},
{
"identifier": "Total",
"categoryId": "1",
"category": "Baked goods",
"price": "454"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Mars Muffin (McVitie's)",
"price": "455"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Secret Recipe",
"price": "471"
},
{
"identifier": "data",
"categoryId": "2",
"category": "Cakes",
"product": "Vimto Jam Tarts",
"price": "235"
},
{
"identifier": "Total",
"categoryId": "2",
"category": "Cakes",
"price": "1161"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Alta Dena",
"price": "158"
},
{
"identifier": "data",
"categoryId": "3",
"category": "Dairy products",
"product": "Chivers",
"price": "399"
},
{
"identifier": "Total",
"categoryId": "3",
"category": "Dairy products",
"price": "557"
}
]