skip to Main Content

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]

Here how the data looks like in Excel: Example Data:enter image description here

3

Answers


  1. You can use slice() to skip the last element (because it has no next value) and map() to generate a new list based on the previous values. Inside the map function, you can use at(i + 1) to get the value of the next value and do some calculation with it. Final code:

    const input = [18240,18290,18340,18400,18470,18510,18600];
    const output = input
      .slice(0, -1)
      .map((num, i) => input.at(i + 1) - num);
    console.log(output);
    Login or Signup to reply.
  2. const data = [18240,18290,18340,18400,18470,18510,18600]
    
    const diffArrays = (data) => {
        const newArray = data.reduce((newObj, item) => {
            if (newObj.previousValue === null) {
                return {
                    previousValue: item,
                    arr: []
                }
            }
    
            return {
                previousValue: item,
                arr: [...newObj.arr, item - newObj.previousValue]
            }
        }, { previousValue: null, arr: []})
    
        return newArray.arr
    }
    
    console.log(diffArrays(data))
    
    Login or Signup to reply.
  3. 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.

    let array = [18240,18290,18340,18400,18470,18510,18600]
    
    let newArray = array.flatMap((elem,idx,self)=>{
    return (idx===array.length-1) ? [] : (self[idx+1]-self[idx])
    
    })
    console.log(newArray)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search