stackoverflow-53305664
https://stackoverflow.com/questions/53305664/how-to-group-elements-to-add-amounts-in-array-with-vue-javascript
by _cole
HTML
<div>
This is something...
</div>
CSS
div {
background-color: red;
}
JavaScript
const roundNumber = (num, scale) => {
if(!("" + num).includes("e")) {
return +(Math.round(num + "e+" + scale) + "e-" + scale);
} else {
var arr = ("" + num).split("e");
var sig = ""
if(+arr[1] + scale > 0) {
sig = "+";
}
return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
}
};
const groupById = data => {
let dataGroup = [];
data.forEach((element) => {
let indexElement = dataGroup.findIndex(elm => {
return (elm.product_id === element.product_id ) && element.print;
});
if(indexElement !== -1) {
dataGroup[indexElement].total += parseFloat(element.total);
dataGroup[indexElement].count += parseInt(element.count);
roundNumber(dataGroup[indexElement].count,0);
roundNumber(dataGroup[indexElement].total,2);
}
else{
dataGroup.push({
id: element.id,
product_id: element.product_id,
total: parseInt(element.total),
count: parseFloat(element.count),
print: !!element.print,
});
}
});
return dataGroup;
}
const data = [
{
"id": 4,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
},
{
"id": 5,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
},
{
"id": 6,
"product_id": 1,
"count": "1.00",
"total": "35.00",
"print": 1
}
];
const grouped = groupById(data);
console.log('grouped', grouped);