Get Sum of Json Array Values

How to sum json array

Working with JSON 101

var foo = {
taxes: [
{ amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"},
{ amount: 25, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"},
{ amount: 10, currencyCode: "USD", decimalPlaces: 0, taxCode: "YRI"}
]
},
total = 0, //set a variable that holds our total
taxes = foo.taxes, //reference the element in the "JSON" aka object literal we want
i;
for (i = 0; i < taxes.length; i++) { //loop through the array
total += taxes[i].amount; //Do the math!
}
console.log(total); //display the result

Sum values from JSON array

In addition to @dauren's answer, here's an alternative way to solve the problem you posted:

json.data.label.
reduce((results, currentServiceObject) => {
let services = Object.keys(currentServiceObject);
services.forEach(billedService => {
currentServiceObject[billedService]
.forEach(monthlyBill => {
let { total_bill, due_date } = monthlyBill;
let monthIndex = new Date(due_date).getMonth();
results[monthIndex] =
results[monthIndex] ?
Number.parseFloat(results[monthIndex]) + Number.parseFloat(total_bill) :
Number.parseFloat(total_bill);
})
});
return results;
}, {})

You'll notice that iteration is a little bit more involved in this case, however, none of the properties or names of the bills (such as "Electricity") need to be known in advance, neither the dates. We just assume (or expect) that objects that represent bills such as "Electricity" conform to an object that is shaped by two properties: 'total_bill' and 'due_date' and that the former contains a string value that represents the billed amount, and the later contains a string representing a date.

The return value of the code above will be an object, in this particular case Object { 5: 217.8, 6: 182.63 } where 5 represents the 6th month in a given year and 6 represents the 7th month.

Count sum of values in JSON array

You could take an array of wanted keys for the sums and create an object for the sums and add the wanted values.

const    data = [{ name: "Dave", coins: 14, weapons: 2, otherItems: 3, color: "red" }, { name: "Vanessa", coins: 18, weapons: 1, otherItems: 5, color: "blue" }, { name: "Sharon", coins: 9, weapons: 5, otherItems: 1, color: "pink" }, { name: "Walter", coins: 9, weapons: 2, otherItems: 4, color: "white" }],    keys = ['coins', 'weapons', 'otherItems'],    sums = data.reduce(        (r, o) => (keys.forEach(k => r[k] += o[k]), r),         Object.fromEntries(keys.map(k => [k, 0]))    );
console.log(sums);

How to sum value of two json object key?

You can use Array#map and then Array#reduce to flatten your object and then sum the result of the map :

bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);

here's a snippet :

var bills = [
{
"refNo": 17,
"billDate": "1-apr-2016",
"dueDate": "30-apr-2016",
"pendingAmount": 4500,
"overdueDays": 28
},
{
"refNo": 20,
"billDate": "15-apr-2016",
"dueDate": "3-may-2016",
"pendingAmount": 56550,
"overdueDays": 15
}
];
var res = bills.map(bill => bill.pendingAmount).reduce((acc, amount) => acc + amount);
console.log(res)

How to get sum of json array

The elements in the array are strings and so, when you use the + operator it concatenates them. You want to parse them first like this:

const sum = quantite.reduce((result,number)=> parseInt(result) + parseInt(number));

SUM query for JSON values in JSON array

You need an additional APPLY operator and a OPENJSON() call with explicit schema (the WITH clause):

Table:

SELECT *
INTO Trend
FROM (VALUES
(N'[{"V":0.1,"T":"07.01.2020 00:10:26"}, {"V":0.2,"T":"07.01.2020 00:10:36"}]')
) v (JsonColumn)

Statement:

SELECT *
FROM Trend t
OUTER APPLY (
SELECT SUM(V) AS V
FROM OPENJSON(t.JsonColumn) WITH (V numeric(5, 1) '$.V')
) j

Result:

JsonColumn                                                                 V
-------------------------------------------------------------------------------
[{"V":0.1,"T":"07.01.2020 00:10:26"}, {"V":0.2,"T":"07.01.2020 00:10:36"}] 0.3

As an additional option - an approach, using JSON_VALUE():

SELECT *
FROM Trend t
CROSS APPLY (
SELECT SUM(TRY_CONVERT(numeric(5, 1), JSON_VALUE([value], '$.V'))) AS V
FROM OPENJSON(t.JsonColumn)
) j

sum up text values in JSON Array

If you don't want to use a library, you could convert all numbers to strings and write your own sum function for strings. This algorithm supports arbitrary long strings containing numbers and returns exact results without rounding errors.

function add(l, r, sep) {
if (!sep) sep = '.';
const [ll, lr] = l.split(/[,.]/).map(el => el.split('').map(Number));
const [rl, rr] = r.split(/[,.]/).map(el => el.split('').map(Number));
let carry = 0;
const result = [[], []];
for (let i = Math.max(lr?.length ?? 0, rr?.length ?? 0); i > 0; --i) {
result[1][i - 1] = (lr?.[i - 1] ?? 0) + (rr?.[i - 1] ?? 0) + carry;
carry = Math.floor(result[1][i - 1] / 10);
result[1][i - 1] %= 10;
}

for (let il = ll.length, ir = rl.length, iResult = Math.max(ll.length, rl.length); iResult > 0; --il, --ir, --iResult) {
result[0][iResult - 1] = (ll[il - 1] ?? 0) + (rl[ir - 1] ?? 0) + carry;
carry = Math.floor(result[0][iResult - 1] / 10);
result[0][iResult - 1] %= 10;
}
if (carry) result[0] = [carry, ...result[0]];
return result[0].join('') + sep + result[1].join('');
}

function sum(arr, sep) {
return arr.map(el => String(el.price)).reduce((acc, el) => add(acc, el, sep));
}

console.log(sum([{ "price": "0.9" }, { "price": "1.2" }], ','));
console.log(sum([{ "price": "100000000" }, { "price": "0.0000002" }]));
console.log(sum([{ "price": 123.123 }, { "price": "1234.5678" }, { "price": "9876,54321" }, { "price": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"}]));

sum of the values of the json array

Using only ES6, you can do this with 2 Array#reduce loops:

const data = [{"id":"name1","c1":"10","c2":"20","c3":"30","c4":"40"},{"id":"name2","c1":"20","c2":"40","c3":"25","c4":"38"}];
const result = data.reduce((sums, obj) => Object.keys(obj).reduce((s, k) => { k === 'id' || (s[k] = (s[k] || 0) + +obj[k]); return s;}, sums), {});
console.log(result);

Sum double values from Json Array

This is just a basis Logical mistake and it has nothing to do with android . You are re initializing totalAmount with 0.0 again and again .

private void sum() {
double totalAmount = 0.0;
for (int i = 0; i < jsonArray2.length(); i++) {
JSONObject jsonObject2 = jsonArray2.getJSONObject(i);
String txN_AMT = jsonObject2.optString("txN_AMT");
totalAmount = totalAmount + Double.parseDouble(txN_BAL_AMT);
}
//outside of the loop, you now have the total amount
Toast.makeText(TenantDetailsActivity.this, "" + totalAmount, Toast.LENGTH_SHORT).show();
}


Related Topics



Leave a reply



Submit