Warm tip: This article is reproduced from stackoverflow.com, please click
arrays ecmascript-6 javascript functional-programming

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

发布于 2020-03-27 10:29:36

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?

Questioner
frans
Viewed
44
Nina Scholz 2019-07-03 01:40

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);