Search code examples
javascriptnode.jsunderscore.jslodash

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 }


Solution

  • 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>