I’m trying to find out how to get the average of change of the Profits/Losses variable
JavaScript
x
5
1
var profitLosses = [867884, 984655, 322013, -69417,
2
310503, 522857, 1033096, 604885, -216386, 477532,
3
893810, -80353, 779806, -335203, 697845, 793163,
4
485070, 584122, 62729, 668179, 899906, 834719, 132003];
5
I’ve used this code below to get the average, but I was wondering if there was a way to get the average of change for the period of time
JavaScript
1
4
1
var avg = (profitLosses / profitLosses.length) || 0;
2
3
console.log(avg)
4
Advertisement
Answer
I assume this is what you’re looking for:
- First you can calculate the changes using map, and putting 0 in the first value of the array.
- Then you sum the changes using reduce.
- Then you divide by the length-1 (because there are one less changes than there are profit&losses)
Also, with this code if your changes are for example +1 then -1 the average would be 0. If you want to look at absolute changes only, you’d have to use Math.abs(item)
in the reduce function.
JavaScript
1
14
14
1
const profitLosses = [
2
867884, 984655, 322013, -69417, 310503, 522857, 1033096, 604885, -216386,
3
477532, 893810, -80353, 779806, -335203, 697845, 793163, 485070, 584122,
4
62729, 668179, 899906, 834719, 132003,
5
];
6
7
const changes = profitLosses.map((element, index) =>
8
index === 0 ? 0 : element - profitLosses[index - 1]
9
);
10
11
const total = profitLosses.reduce((acc, item) => acc + item, 0);
12
const averageChange = total / (profitLosses.length - 1);
13
14
console.log(averageChange);