I have an array of increasing numbers representing energy meter values, either weekly, monthly, or yearly:
[18240,18290,18340,18400,18470,18510,18600]
I’m looking for a function in javascript.
Desired output is the difference between the next element e.g.:
[50,50,60,70,40,90]
3
Answers
You can use
slice()
to skip the last element (because it has no next value) andmap()
to generate a new list based on the previous values. Inside the map function, you can useat(i + 1)
to get the value of the next value and do some calculation with it. Final code:You can use flatMap to loop through your array and return the difference of element and the previous one into the new array. When it reaches the last element will return an empty array as there is no next element, this empty array is removed by flatMap method.