Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 783
frans Avatar asked Jan 01 '23 20:01

frans


2 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);
like image 103
Nina Scholz Avatar answered Jan 08 '23 01:01

Nina Scholz


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)
like image 28
Nenad Vracar Avatar answered Jan 08 '23 01:01

Nenad Vracar