Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most efficient way to find average using lodash

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.

like image 380
meajmal Avatar asked Jan 29 '15 11:01

meajmal


People also ask

Is Lodash efficient?

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.

How do you find the average of an array?

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.

How do you calculate average in JavaScript?

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.

How do you average an array in JavaScript?

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.


1 Answers

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

like image 105
Frederic Yesid Peña Sánchez Avatar answered Sep 30 '22 06:09

Frederic Yesid Peña Sánchez