简体   繁体   中英

Lodash - use meanBy with multiple properties

I have this array :

arr = [{a:1, b:2},
       {a:3, b:6}]

Using lodash, I want to get the mean of this array, like this:

{a:2, b:4}

For only one property I can use _.meanBy(arr, 'a') . Is there a similar syntax to get the mean for more than 1 property at the same time? Something that would look like _.mean(arr, ['a', 'b'])

It would be nicer than using meanBy twice as I suppose that there would only be one loop over the array...

You can use lodash#mergeWith wrapped in a lodash#spread to treat the entire array as arguments. Use lodash#concat to provide the arguments together with the lodash#add callback. Note that using an empty object as first argument makes sure that the items in the array aren't mutated.

var result = _.spread(_.mergeWith)(_.concat({}, arr, function(a,b) {
  return _.add(a, (b || 0) / arr.length);
}));

 var arr = [{ a: 1, b: 2 }, { a: 3, b: 6 } ]; var result = _.spread(_.mergeWith)(_.concat({}, arr, function(a,b) { return _.add(a, (b || 0) / arr.length); })); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

You can use Array#reduce with Array#forEach to get an object of averages.

 var arr = [{a:1, b:2}, {a:3, b:6}]; var result = arr.reduce(function(mean, obj) { Object.keys(obj).forEach(function(key) { mean[key] = (mean[key] || 0) + obj[key] / arr.length; }); return mean; }, {}); console.log(result); 

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