I have an array of objects, the number of objects is variable -
var people = [{
name: john,
job: manager,
salary: 2000
},
{
name: sam,
job: manager,
salary: 6000
},
{
name: frodo,
job: janitor
}];
Whats the most elegant way to find the average of the salaries of all managers using lodash? ( I assume we have to check if an object is manager, as well as if the object has a salary property)
I was thinking in the below lines -
_(people).filter(function(name) {
return name.occupation === "manager" && _(name).has("salary");}).pluck("salary").reduce(function(sum,num) { return sum+num });
But I am not sure if this is the right approach.
Why all people gets over-complicated here?
const people = [
{ name: 'Alejandro', budget: 56 },
{ name: 'Juan', budget: 86 },
{ name: 'Pedro', budget: 99 },
];
const average = _.meanBy(people, (p) => p.budget);
console.log(average);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
As per the docs: https://lodash.com/docs/#meanBy