简体   繁体   中英

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| ba }

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

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> 

也许是更惯用的lodash解决方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM