Brian Smith
Brian Smith

Reputation: 145

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 }

Upvotes: 3

Views: 1390

Answers (4)

yonilevy
yonilevy

Reputation: 5428

Perhaps a more idiomatic lodash solution:

_.zipWith(arr.slice(1), arr.slice(0, -1), _.subtract)

Upvotes: 1

mostruash
mostruash

Reputation: 4189

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

Upvotes: 1

Mark T
Mark T

Reputation: 795

How about using _.reduce:

(function () {
    var nums = [0,4,3,9,10];
    var diffs = _.reduce(nums, function(result, value, index, collection) {
        if (index === 0) return result;
        result[index] = value - collection[index - 1];
        return result;
    }, []).slice(1);
    
    $('.output').text(JSON.stringify(diffs));
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.3/lodash.min.js"></script>
<div class=output></div>

Upvotes: 0

Pavan Ravipati
Pavan Ravipati

Reputation: 1870

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>

Upvotes: 5

Related Questions