Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash calculate difference between array elements

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 }

like image 253
Brian Smith Avatar asked Sep 02 '26 23:09

Brian Smith


2 Answers

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>
like image 119
Pavan Ravipati Avatar answered Sep 05 '26 13:09

Pavan Ravipati


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]);
like image 35
mostruash Avatar answered Sep 05 '26 12:09

mostruash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!