In JavaScript how do I create a list of differences of array elements elegantly?

Viewed 283

I have a list of numbers, say numbers = [3,7,9,10] and I want to have a list containing the differences between neighbor elements - which has to have one less element - in the given case diffs = [4,2,1]

Of course I could create a new list go through the input list and compile my result manually.

I'm looking for an elegant/functional (not to say pythonic) way to do this. In Python you would write [j-i for i, j in zip(t[:-1], t[1:])] or use numpy for this.

Is there a reduce()/list comprehension approach in JavaScript, too?

6 Answers

You could slice and map the difference.

var numbers = [3, 7, 9, 10],
    result = numbers.slice(1).map((v, i) => v - numbers[i]);

console.log(result);

A reversed approach, with a later slicing.

var numbers = [3, 7, 9, 10],
    result = numbers.map((b, i, { [i - 1]: a }) => b - a).slice(1);

console.log(result);

You could do this using reduce method

const numbers = [3, 7, 9, 10]
const res = numbers.reduce((r, e, i, a) => i ? r.concat(e - a[i - 1]) : r, []);
console.log(res)

You could also pop after map:

var numbers = [3, 7, 9, 10],
result = numbers.map((v, i) => numbers[i+1]-v);
result.pop()

console.log(result);

you can use map and slice

const numbers = [3, 7, 9, 10, 11, 13];


const res = numbers.map((num, index) => numbers[index + 1] - num).slice(0, -1);



console.log(res)

You can use destructuring assignment and recursion -

const diff = ([ a, b, ...more ]) =>
  b === undefined
    ? []
    : [ b - a, ...diff ([ b, ...more ]) ]
    
 
console .log (diff ([ 3, 7, 9, 10 ]))
// [ 4, 2, 1 ]

console .log (diff ([ 3 ]))
// []

console .log (diff ([]))
// []

Or skip some intermediate values by using an index -

const diff = (a = [], i = 1) =>
  i >= a.length
    ? []
    : [ a[i] - a[i - 1], ...diff (a, i + 1) ]
    
console .log (diff ([ 3, 7, 9, 10 ]))
// [ 4, 2, 1 ]

console .log (diff ([ 3 ]))
// []

console .log (diff ([]))
// []

If needed, make it stack-safe using loop and recur. This one runs really fast, too -

const recur = (...values) =>
  ({ recur, values })
  
const loop = f =>
{ let r = f ()
  while (r && r.recur === recur)
    r = f (...r.values)
  return r
}

const push = (a = [], v) =>
  ( a .push (v)
  , a
  )
  
const diff = (a = []) =>
  loop
    ( ( i = 1
      , r = []
      ) =>
        i >= a.length
          ? r
          : recur
              ( i + 1
              , push (r, a[i] - a[i - 1])
              )
    )
    
console .log (diff ([ 3, 7, 9, 10 ]))
// [ 4, 2, 1 ]

console .log (diff ([ 3 ]))
// []

console .log (diff ([]))
// []

You can slice (0 as a start, -1 to skip the last item) and map so to generate the differences between an element and its successor in the sequence:

    const items = [3,7,9,10];
    console.log(items.slice(0,-1).map((e,i)=>items[i+1]-e))

Related