Creating an array of object with cumulative sum dynamically in javascript
If you want to cumulatively sum every property other than subject
, you can do so by mapping the array to new values, keeping an object reference for each running total as you go
const a = [{"subject":"Civil","a":100,"b":50,"c":100},{"subject":"aero","a":200,"b":130,"c":100},{"subject":"tribe","a":100,"b":100,"c":600},{"subject":"solen","a":400,"b":150,"c":100},{"subject":"space","a":100,"b":100,"c":900}]
const cf = {} // store running totals in here
const b = a.map(({ subject, ...props }) => ({
subject,
...Object.fromEntries(Object.entries(props).map(([ key, val ]) => [
key,
cf[key] = (cf[key] ?? 0) + val // value is the result of the assignment
]))
}))
console.log(b)
.as-console-wrapper { max-height: 100% !important; }
Running sum of the input array in Javascript
Just add first item in array initialization and everything works fine.
function sumOfArray(nums) {
var output = [nums[0]]; // tip: initialize like let output = [nums?.[0] ?? 0];
for(let i = 1 ; i < nums.length ; i++) {
nums[i] = nums[i] + nums[i-1];
output.push(nums[i]);
}
return output;
};
console.log(
'calling sumOfArray([1,2,3,4])',
sumOfArray([1,2,3,4])
);
Creating an array of objects with cumulative sum in javascript
You are slicing the original array data
, but you need to take the sorted accumulated
.
For a shorter approach, you could take a closure over the wanted cumulative sums and add the values and return a new object.
const
original = [{ end_date: "2020-01-31", invoices_count: 22, month: "2020-01", start_date: "2020-01-01", total_margin: 1000, total_revenue: 1000 }, { end_date: "2020-02-29", invoices_count: 14, month: "2020-02", start_date: "2020-02-01", total_margin: 2000, total_revenue: 2000 }],
result = original.map(((total_margin, total_revenue) => o => {
total_margin += o.total_margin;
total_revenue += o.total_revenue;
return { ...o, total_margin, total_revenue };
})(0, 0));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Cumulative sum array in Javascript, one is working and one is not
The problem lies in the way you are using cumulativeSum
You are trying a function reference and using it between two arrays, because of that when you call the second array the sum
already has some value in it. The fix will look in the following way
function tickets(peopleInLine) {
let changeRequired = [];
const cumulativeSum = (sum => value => sum += value);
let cumulativeProfit = peopleInLine.map(cumulativeSum(0));
cumulativeProfit.splice(0, 0, 0);
cumulativeProfit.pop();
for (let i = 0; i < peopleInLine.length; i++) {
if (peopleInLine[i] === 25) { changeRequired.push(0) }
else if (peopleInLine[i] === 50) { changeRequired.push(25) }
else if (peopleInLine[i] === 100) { changeRequired.push(75) }
};
let cumulativeOutgoings = changeRequired.map(cumulativeSum(0));
cumulativeOutgoings.splice(0, 0, 0);
cumulativeOutgoings.pop();
return cumulativeOutgoings;
};
Cumulative sum of object properties in array
const arr = [{
"soldTickets": 0,
"soldRevenue": 0,
"playedOffTickets": 0,
"playedOffRevenue": 0,
"advanceTickets": 11407,
"advanceRevenue": 284222.5,
"occurredAt": "",
"changeInPeriodTickets": 0,
"changeInPeriodRevenue": 0,
"eopAdvanceTickets": 11407,
"eopAdvanceRevenue": 284222.5
}, {
"soldTickets": 0,
"soldRevenue": 0,
"playedOffTickets": 112,
"playedOffRevenue": 3151.5,
"advanceTickets": 0,
"advanceRevenue": 0,
"occurredAt": "2022-01-14T00:00:00.000",
"changeInPeriodTickets": -112,
"changeInPeriodRevenue": -3151.5,
"eopAdvanceTickets": -112,
"eopAdvanceRevenue": -3151.5
}, {
"soldTickets": 0,
"soldRevenue": 0,
"playedOffTickets": 392,
"playedOffRevenue": 13592,
"advanceTickets": 0,
"advanceRevenue": 0,
"occurredAt": "2022-01-09T00:00:00.000",
"changeInPeriodTickets": -392,
"changeInPeriodRevenue": -13592,
"eopAdvanceTickets": -392,
"eopAdvanceRevenue": -13592
}, {
"soldTickets": 0,
"soldRevenue": 0,
"playedOffTickets": 502,
"playedOffRevenue": 18415.5,
"advanceTickets": 0,
"advanceRevenue": 0,
"occurredAt": "2022-01-08T00:00:00.000",
"changeInPeriodTickets": -502,
"changeInPeriodRevenue": -18415.5,
"eopAdvanceTickets": -502,
"eopAdvanceRevenue": -18415.5
}];
const result = arr.map((obj, index, self) => {
if (index == 0) return obj;
const prevO = self[index - 1]
obj.eopAdvanceTickets+= prevO.eopAdvanceTickets;
obj.eopAdvanceRevenue+= prevO.eopAdvanceRevenue;
return obj
});
console.log(result)
Multi dimensional array cumulative sum in Javascript
for (var i=1; i<a.length; i++) {
for (var z=0; z<a[i].length; z++) {
a[i][z] = a[i-1]][z] + a[i][z]
}
}
The array should be updated dynamically as the loop runs on.
This is destructive so it will modify the original array.
Cumulative sum of array, with condition in another array
You're making life far too hard on yourself with all that pushing and reducing and shifting.
function running_total(array, init) { return array .map(function(v, i) { return v ===3 ? 0 : v; }) // filter out 3's .map(function(v) { return init += v; }) ;}
document.writeln(running_total([1,2,3,4,5], 0));
Cumulative sum of specific keys with array output using reduce
Something like this:
const arr = [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: -1}]
const result = arr.reduce((accumulator, element, index) => {
if(accumulator.length === 0) {
accumulator.push(element)
} else {
const sum = {};
for(let i in element) {
sum[i] = element[i] + (accumulator[index - 1][i] || 0)
}
accumulator.push(sum)
}
return accumulator
}, [])
console.log(result);
Related Topics
Node.Js Async/Await Using with MySQL
Understanding JavaScript Scope with "Var That = This"
What's Pros and Cons: Putting JavaScript in Head and Putting Just Before the Body Close
Settimeout/Cleartimeout Problems
How to Read a Text File from Server Using JavaScript
Case Insensitive String Replacement in JavaScript
How to JSON Stringify a JavaScript Date and Preserve Timezone
How to Trigger a Bootstrap Modal Programmatically
Regex Pattern to Match the End of a String
How to Populate the Options of a Select Element in JavaScript
Get Index of Clicked Element Using Pure JavaScript
$.Each() VS For() Loop - and Performance
How to Access Parent Window Object Using Jquery
How to Block Users from Closing a Window in JavaScript
React Usestate Hook Event Handler Using Initial State
Get Function Name in JavaScript
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser