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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With