Skip to content
Advertisement

Finding out how to find out the Profit/Losses average of change in this array [closed]

I’m trying to find out how to get the average of change of the Profits/Losses variable

var profitLosses = [867884, 984655, 322013, -69417,
  310503, 522857, 1033096, 604885, -216386, 477532,
  893810, -80353, 779806, -335203, 697845, 793163,
  485070, 584122, 62729, 668179, 899906, 834719, 132003];

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

var avg = (profitLosses / profitLosses.length) || 0;

console.log(avg)

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.

const profitLosses = [
  867884, 984655, 322013, -69417, 310503, 522857, 1033096, 604885, -216386,
  477532, 893810, -80353, 779806, -335203, 697845, 793163, 485070, 584122,
  62729, 668179, 899906, 834719, 132003,
];

const changes = profitLosses.map((element, index) =>
  index === 0 ? 0 : element - profitLosses[index - 1]
);

const total = profitLosses.reduce((acc, item) => acc + item, 0);
const averageChange = total / (profitLosses.length - 1);

console.log(averageChange);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement