maxd
maxd

Reputation: 73

Lodash using pickBy instead of each

Hello I have a question to refactor my code using lodash, I did a program to calculate the mean of integers of an object. I would like to use a _.pickBy instead of a _.each.

This is my program with an _.each :

var my_obj = {a: 1, b:2, c: 'foo', d: 'bar', w:3, z:4};

function mean(obj) {
  var temp=0;
  var count=0;
  _.each(obj, function(value, key){
    if(_.isNumber(value)){
      result +=  value
      count += 1
    }
  })
  return temp / count;
}
mean(my_obj)  //outputs is 2.5 in this exemple

I'm stuck using _isNumber with the _.pickBy :

function mean(obj) {
  var result = 0
  return _.pickBy(obj, function(value, key){
    return _.isNumber{(value) 
    // how to have the sum and divise by the number of integer objects ?
  })
}

Upvotes: 1

Views: 3889

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Since you want an array of numbers, and not an object, use _.filter() with _.isNumber() to get an array of numbers, then return the the _.mean() of the array:

function mean(obj) {
  return _.mean(_.filter(obj, _.isNumber));
}

var my_obj = {a: 1, b:2, c: 'foo', d: 'bar', w:3, z:4};

console.log(mean(my_obj));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

Upvotes: 2

Related Questions