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.
Lodash is extremely well-optimized as far as modern JS goes, but, as you may know, nothing can be faster than native implementation. Even if Lodash uses the same API under-the-hood, function call overhead is still present. Some might say that these are just some micro-optimizations.
Simple approach to finding the average of an array We would first count the total number of elements in an array followed by calculating the sum of these elements and then dividing the obtained sum by the total number of values to get the Average / Arithmetic mean.
You calculate an average by adding all the elements and then dividing by the number of elements. var total = 0; for(var i = 0; i < grades. length; i++) { total += grades[i]; } var avg = total / grades.
To calculate the average of an array in JavaScript: Sum all the values of the array. Divide the sum by the length of the array.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With