How to group by and sum an array of objects?
You can loop and sum it up
var array = [ { Id: "001", qty: 1 }, { Id: "002", qty: 2 }, { Id: "001", qty: 2 }, { Id: "003", qty: 4 }];
var result = [];array.reduce(function(res, value) { if (!res[value.Id]) { res[value.Id] = { Id: value.Id, qty: 0 }; result.push(res[value.Id]) } res[value.Id].qty += value.qty; return res;}, {});
console.log(result)
Group by, and sum, and generate an object for each array in JavaScript
You can try this:
const result = Object.values(data.reduce((r, o) => (r[o.id]
? (r[o.id].total += o.total)
: (r[o.id] = {...o}), r), {}));
how to group and sum data in foreach javascript
you can use reduce
usually for these grouping problems. I'm taking the combination of code
and date
to group. something like "8|2022-03-24"
.
This is how the intermediate object will look like
{
8|2022-03-24: {
code: 8,
date: "2022-03-24",
total: 12
},
8|2022-03-25: {
code: 8,
date: "2022-03-25",
total: 2
},
9|2022-03-24: {
code: 9,
date: "2022-03-24",
total: 4
},
9|2022-03-25: {
code: 9,
date: "2022-03-25",
total: 3
}
}
From that object I'm taking the values using Object.values
const data = [
{code: 8, date:"2022-03-24", total:4},
{code: 8, date:"2022-03-24", total:8},
{code: 8, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-24", total:4},
{code: 9, date:"2022-03-25", total:2},
{code: 9, date:"2022-03-25", total:1},]
let grouped = Object.values(data.reduce((acc,{code,date,total})=>{
acc[code+'|'+date] = acc[code+'|'+date] || {code,date,total:0}
acc[code+'|'+date].total+=total
return acc;
},{}))
console.log(grouped)
Javascript array of objects group and sum items
This works fine
Object.values(
cars.reduce((agg, car) => {
if (agg[car.make] === undefined) agg[car.make] = { make: car.make, sumQuantity: 0 }
agg[car.make].sumQuantity += +car.quantity
return agg
}, {})
)
How to group by and sum an array of objects javascript?
You group the array into an object, where the keys are concatenation of available
and id
properties and finally transform the object back to an array using Object.values
.
const
array = [
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 10 }, available: "no" } },
{ data: { qty: "59", toy: { id: 10 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
],
result = Object.values(
array.reduce((r, { data }) => {
const k = data.available + data.toy.id;
if (r[k]) {
r[k].data.qty = String(Number(r[k].data.qty) + Number(data.qty));
} else {
r[k] = { data };
}
return r;
}, {})
);
console.log(result);
GroupBy array of objects to new array and sum value
Looking at your initial array and the output you wanted to get, below are the examples that result in exactly the same structure as per your question - an array of arrays of objects
One way with find
& for of loop
:
let arr = [
{
"year": "202003",
"cost": 11194.55,
"type": "A"
},
{
"year": "202003",
"cost": 60.2,
"type": "B"
},
{
"year": "202003",
"cost": 747.12,
"type": "C"
},
{
"year": "202003",
"cost": 747.12,
"type": "D"
},
{
"year": "202004",
"cost": 747.12,
"type": "D"
},
{
"year": "202003",
"cost": 4674.59,
"type": "D"
}
]
let sortedArray = []
for (let [index, el] of arr.entries()) {
if(sortedArray.find(elInner => (elInner[0].type === el.type && elInner[0].year !== el.year))) {
sortedArray.find(elInner => elInner[0].type === el.type).push(arr[index])
}else if (sortedArray.find(elInner => (elInner[0].type === el.type && elInner[0].year == el.year))) {
sortedArray.find(elInner => (elInner[0].type === el.type && elInner[0].year == el.year))[0].cost += arr[index].cost
}else {
sortedArray.push([el])
}
}
console.log(sortedArray)
how to group by and total sum array of object in javascript?
You could try something like this
const output = Object.entries(groupByMonth).map(([time, datapoints]) => {
const codes = {}
const allTasks = datapoints.flatMap(point => point.task)
for (const { code, value } of allTasks) {
codes[code] = (codes[code] || 0) + value
}
return {
time,
tasks: Object.entries(codes).map(([code, value]) => ({ code, value }))
}
}
Though one downside is that the time complexity isn't perfect because of the structure of the data
Related Topics
How to Convert Gmt Time to Ist Time in JavaScript
How to Convert Raw Mp3 Binary into Blob Url and Play It in Audio Tag
Keep Selected Dropdown Result After Refreshing Page, Jquery
How to Hide Select Options With Javascript (Cross Browser)
How to Change Colour of Text Based on Its Value When a Page Initially Loads
How to Cancel Ongoing Http Requests When There's a New Requests in Angular 6 With Rxjs 6
How to Clear Browsing History Using JavaScript
How Could I Get the Latest Date from an Array of Dates - Javascript/Typescript
How to Download Pdf Automatically Using Js
Show Virtual Keyboard on Mobile Phones in JavaScript
Check If Image Exists on Server Using JavaScript
How to Create Expand/Collapse Function for Each Row of Table - Angular6
How to Change Color of Ag-Grid Cells for Dynamically Changing Data
Check If Current Time Is Between Two Given Times in JavaScript
It Is Possible to Call Class Function from Outside Class
Jquery: Simplest Way to Check Url for a Parameter and Pass It to Anchor Href If It Exists