Javascript Sum and Group by of Json Data

JavaScript SUM and GROUP BY of JSON data

You can use the native functions .reduce() to aggregrate the data, and then .sort() to sort by bytes.

var result = dataObject.reduce(function(res, obj) {
if (!(obj.category in res))
res.__array.push(res[obj.category] = obj);
else {
res[obj.category].hits += obj.hits;
res[obj.category].bytes += obj.bytes;
}
return res;
}, {__array:[]}).__array
.sort(function(a,b) { return b.bytes - a.bytes; });

If you're supporting older implementations, you'll need to use a shim for .reduce().

Nested object reduce group by and sum - javascript

You can easily achieve this result using reduce

If some case grade key increases then you can add dynamic code so that it can work with infinite keys in grade. Just replace

isExist.grade.grade1 += grade.grade1;
isExist.grade.grade2 += grade.grade2;
isExist.grade.grade3 += grade.grade3;

with

Object.keys(isExist.grade).forEach((key) => {
isExist.grade[key] += curr.grade[key];
});

const obj = {
data: [
{
name: "france Naicin",
avgTotalWeight: 16,
grade: {
grade1: 16,
grade2: 0,
grade3: 0,
},
},
{
name: "pacific gigas",
avgTotalWeight: 16,
grade: {
grade1: 16,
grade2: 0,
grade3: 0,
},
},
{
name: "france Naicin",
avgTotalWeight: 13,
grade: {
grade1: 13,
grade2: 0,
grade3: 0,
},
},
{
name: "france Naicin",
avgTotalWeight: 14,
grade: {
grade1: 14,
grade2: 0,
grade3: 0,
},
},
{
name: "france Naicin",
avgTotalWeight: 15,
grade: {
grade1: 15,
grade2: 0,
grade3: 0,
},
},
],
};

const result = obj.data.reduce((acc, curr) => {
const { name, avgTotalWeight, grade } = curr;
const isExist = acc.find((o) => o.name === name);
if (isExist) {
isExist.weightTotal += avgTotalWeight;
isExist.grade.grade1 += grade.grade1;
isExist.grade.grade2 += grade.grade2;
isExist.grade.grade3 += grade.grade3;
} else {
acc.push({
name,
weightTotal: avgTotalWeight,
grade,
});
}
return acc;
}, []);

console.log(result);

Group sum and transform json object with values in nested array

You could use this transformation:

const result = Object.values(myList.reduce( (acc, o) => {
const month = o.date.substr(5,2) + '/' + o.date.substr(2,2);
return o.items.reduce ( (acc, item) => {
const it = acc[item.itemId] || {
itemId: item.itemId,
period: {}
},
m = it.period[month] || {
month: month,
quantity: 0,
cost: 0
};
m.cost += item.itemCost * item.itemQuantity;
m.quantity += item.itemQuantity;
it.period[month] = m;
acc[item.itemId] = it;
return acc;
}, acc);
}, {})).map( o =>
Object.assign({}, o, { period: Object.values(o.period) })
);

const myList = [{     "orderId" : "01",    "date" : "2017-01-02T06:00:00.000Z",    "items" : [        {            "itemId": 100,            "itemCost": 12,            "itemQuantity": 10        },        {            "itemId": 102,            "itemCost": 25,            "itemQuantity": 4        }    ]},{    "orderId": "02",    "date" : "2017-01-08T06:00:00.000Z",    "items" : [        {            "itemId": 100,            "itemCost": 15,            "itemQuantity": 2        },        {            "itemId": 101,            "itemCost": 20,            "itemQuantity": 5        },        {            "itemId": 102,            "itemCost": 25,            "itemQuantity": 1        }    ]},{    "orderId": "03",    "date" : "2017-02-08T06:00:00.000Z",    "items" : [        {            "itemId": 100,            "itemCost": 15,            "itemQuantity": 2        },        {            "itemId": 101,            "itemCost": 20,            "itemQuantity": 5        },        {            "itemId": 102,            "itemCost": 25,            "itemQuantity": 1        }    ]}];
const result = Object.values(myList.reduce( (acc, o) => { const month = o.date.substr(5,2) + '/' + o.date.substr(2,2); return o.items.reduce ( (acc, item) => { const it = acc[item.itemId] || { itemId: item.itemId, period: {} }, m = it.period[month] || { month: month, quantity: 0, cost: 0 }; m.cost += item.itemCost * item.itemQuantity; m.quantity += item.itemQuantity; it.period[month] = m; acc[item.itemId] = it; return acc; }, acc);}, {})).map( o => Object.assign({}, o, { period: Object.values(o.period) }) );
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

group and sum json object javascript

You can use Array#reduce method to generate the object.

var data = {"topic_id": {"0": 1, "1": 1, "6": 2, "8": 2,  "12": 3, "13": 3, "18": 4, "20": 4, },"score": { "0": 1,  "1": 3, "6": 2, "8": 3, "12": 3, "13": 1, "18": 3,  "20": 3, }};
// variable for holding the index reference of idvar ref = {}, // counter variable for property name, you can avoid if you are using array i = 0;
console.log( // get kesy of topic_id Object.keys(data.topic_id) // iterate over the property names .reduce(function(obj, k) { // check id refernce present already if (data.topic_id[k] in ref) { // if present then update the score obj.score[ref[data.topic_id[k]]] += data.score[k]; } else { // if not present add reference in the ref object ref[data.topic_id[k]] = i++; // add entry in topic_id obj.topic_id[ref[data.topic_id[k]]] = data.topic_id[k]; // add score value obj.score[ref[data.topic_id[k]]] = data.score[k]; } // return the object reference return obj; // set initial value as our prefered object format }, {topic_id: {}, score: {}}))

SUM and GROUP BY on multiple fields of JSON data using Linq.js

Basically you're looking for a two-tiered grouping. First an overall grouping of all companies, and within each group, a grouping of foci. There's many different ways this could be modeled, but the most straight forward way:

var query = Enumerable.From(data)
.GroupBy("$.Company", null,
function (key, g) {
return {
Company: key,
Result: Enumerable.From(g)
.GroupBy("$.Focus", null,
"{ Focus: $, Completed: $$.Sum('Number($.Completed)'), Remaining: $$.Sum('Number($.Remaining)') }"
)
.ToArray()
};
}
)
.ToArray();

Note the use of the Number() function. Since the Completed and Remaining properties are strings, taking the sum will not quite work as expected. We need to convert them to numbers beforehand.

Group JSON data depending on the first 3 columns and sum the number of the 4th column in HTML/JS

I've created the following answer, I hope it meets your needs.

var data = {  "headers":["plat","chan","group","cat","num"],  "rows":[      ["plat1","chan1","bbb","cat1",222],    ["plat1","chan1","bbb","cat1",333],    ["plat1","chan1","bbb","cat2",850]  ]};

function transformData(rows) { const rowMap = new Map(), result = []; // Iterate over the rows. rows.forEach(row => { const // Create a key, it is the first 4 elements joined together. key = row.slice(0,4).join(); // Check if the Map has the generated key... if (rowMap.has(key)) { // The map has the key, we need to add up the values const // Get the value for the current key. storedRow = rowMap.get(key); // Add the value of the current row to the row in the map. storedRow[4] += row[4]; } else { // The key doens't exist yet, add the row to the map. rowMap.set(key, row); } }); // Iterate over all the entries in the map and push each value with the // summed up value into the array. rowMap.forEach(value => { result.push(value); }); // Return the array. return result; }
// Creates cells for all items in the row array. When no cell type is set// the method will create td elements.function getCells(row, element = 'td') { // Reduce the array to a single string. return row.reduce((result, cell) => { result += `<${element}>${cell}</${element}>`; return result; }, '');}
// Creates tr elements for each item in the rows array, each tr element// will be filled with td elements.function getBody(rows) { // Reduce the array to a single string. return rows.reduce((result, row) => { result += `<tr>${getCells(row)}</tr>` return result; }, '');}
// Create the HTML table.function createTable(tableData) { let tableHTML = ''; tableHTML = `<table> <thead><tr>${getCells(tableData.headers, 'th')}</tr></thead> <tbody>${getBody(tableData.rows)}</tbody> </table>`; return tableHTML;}

data.rows = transformData(data.rows);const generateHTML = createTable(data);$("#two").html(generateHTML);
@import url('https://fonts.googleapis.com/css?family=Roboto');
body { margin: 0; color:#fff; font-family: Roboto; }.row { display: table; width: 100%; height: 241px; background-color:#454545;}.row > .col-lg-6 { display: table-cell; vertical-align: middle;}.container { /*display: flex;*/ flex-wrap: wrap;}.container > div { padding: 15px; margin: 5px; flex: 0 0 calc(100% - 20px); text-align: left;}
/*img { padding-left: 7%; max-height:55px; width:auto;}*/td{ padding: 2px 2px; text-align: center; margin: 6px 0; border: none;}table{ width: 100%; background-color:#454545; font-weight:500; border-collapse: separate; border-spacing:0.3em 1.1em; color: #fff; border: 0;}tr{ font-size: 1.5em; text-transform:capitalize;}tr:nth-child(1) { color: #CCC; font-size: 1.5em; } #one,#two,#three,#four{ padding-top:2%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 style="color:#000;">Result table (dynamic).</h4><div id="two"></div>
<h4 style="color:#000;">Table that I want to get (static)</h4><div><table> <thead> <tr> <th>plat</th> <th>chan</th> <th>cat</th> <th>num</th> </tr></thead> <tbody> <tr> <td>plat1</td><td>chan1</td><td>cat1</td><td>555</td></tr><tr> <td>plat1</td><td>chan1</td><td>cat2</td><td>850</td></tr></tbody></table></div>

How to GROUP and SUM json data using angular/ionic?

the transformation is just a logical part, your ng-repeat and all you can use then to render that in UI how you want.

here I am writing a function that will do the job for you

function populateSumArray(inputClasses) {
opClasses = [];
inputClasses.forEach(function(item) {
var existing = opClasses.find(function(each) {
return each.Class === item.Class;
});
if (existing) {
existing.StudentCount = parseInt(existing.StudentCount) + parseInt(item.StudentCount);
} else {
opClasses.push(item);
}
});
return opClasses;
}

and you can call this to transform it to a new array (calculated) and store it whereever you need. If you want to update the same scope variable then here is an example

$scope.Classes = populateSumArray($scope.Classes)

hope, it helps :)

Sum up JSON array items by common key

You may walk through your source array, using Array.prototype.reduce() and insert into resulting array item, having product value found for the first time, or add current quantity should one already exist: