I have a time series item which contains energy prices of the next day and I would like to grab the lowest x prices of that day (with timestamp) and add them to other items.
With the help of Blockly I came up with this already. This code grabs all items of tomorrow and returns this string:
Actually, it’s not a String. It’s an array of two element arrays (first element is the timestamp, second is the value). You’ll need to use a loop and variables to loop through the array to find the minimum value and tiemstamp for that Item.
But how can I loop this multiple times (eg 5 times) to get the 2nd lowest value, 3rd lowest… and store it in a new array?
Or maybe it’s easier to sort my array based on the value and then get the first X of them?
(a, b) => { }: this is a way to define an anonumous function in JavaScript that takes two arguments. sort() can take such a function to dictate how it sorts the array. From the docs:
It should return a number where:
A negative value indicates that a should come before b.
A positive value indicates that a should come after b.
Zero or NaN indicates that a and b are considered equal.
I could have written it shorter but I wrote it out long form to make it more clear how it works. The short form would be
prices_00_24 = prices_00_24.sort((a, b) => a[1]-b[1]);
a[1] and b[1]: the sort() method will call this function with two arguments, a and b which are two elements of the array. We know that the elements of the array is itself a two element array where the value is the second element. We want to sort by the second element so we compare the second element which is index [1].