0

I have an array called sales, shown below.

I have a function that calculates the standard deviation (bottom of the post) of the amounts.

I am trying to use the slice function but having some issues. I want to take a slice of my Sales array say the 10th row up to the 50th row and pass it to my standard deviation function.

 Sales : Array(500)
 0: {DateSale: "2018-01-01T00:00:00", Currency: "USD", Amount: 325} 
 1: {DateSale: "2018-01-02T00:00:00", Currency: "USD", Amount: 6832}
 ...

The below line doesn't work

standardDevation(Sales.Amount.slice(10,50));

Error message,

Uncaught TypeError: Cannot read property 'slice' of undefined

The line below works in that the slice function is applied. However my standardDevation function returns NaN. I know I can change the values to values.Amount in my standard deviation but I want to know if its possible to just slice the Amount field of my Sales array? Because if I want to calculate the standard deviation of another array and it doesn't have the field Amount I assume it won't work?

standardDevation(Sales.slice(10,50));

function standardDeviation(values) {
var avg = average(values);

var squareDiffs = values.map(function (value) {
    var diff = value - avg;
    var sqrDiff = diff * diff;
    return sqrDiff;
});

var avgSquareDiff = average(squareDiffs);

var stdDev = Math.sqrt(avgSquareDiff);
return stdDev;
}
mHelpMe
  • 6,336
  • 24
  • 75
  • 150
  • Possible duplicate of [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Sebastian Simon Jul 16 '18 at 13:13

1 Answers1

2

You want to get the slice of your Sales array and then map the output to get an array of numbers to pass to your function:

standardDevation(Sales.slice(10,50).map(s => s.Amount));
Paddy
  • 33,309
  • 15
  • 79
  • 114