In javascript using lodash, I need a way to calculate the difference between array elements, for instance:
With an array of
[0,4,3,9,10]
I need to get the difference between each element.
output should be
[4,-1,6,1]
How would I do this using lodash?
In ruby it looks something like this:
ary.each_cons(2).map { |a,b| b-a }
One possible solution is with using _.map():
var arr = [0,4,3,9,10];
var result = _.map(arr, function(e, i) {
return arr[i+1] - e;
});
result.pop();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>
You could do something do something like this:
var arr = [0, 4, 3, 9, 10];
var res = [];
_.reduce(_.rest(arr), function (prev, next) {
res.push(next - prev);
return next;
}, arr[0]);
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