DEV Community

Rajnish Katharotiya
Rajnish Katharotiya

Posted on

Get average of a given array or multi records in javascript

Hello amazing people, Welcome again in a new episode of series called javascript useful snippets. In this series, I’m going to talk about some shortcodes and useful functions of javascript. These snippets can help you to make your development more efficient and faster. Stay tuned till the end to learn something new… 😊

Javascript Useful Snippets — average()

While developing, getting an average of multiple values is just another task which you need to do most often. average() snippet can be used to get the average of a given record. let’s see syntax of function…..

const average = (…nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length

In function, I’ve used spread all arguments which passed through calling. and have stored it into a nums variable. ( for your knowledge — spreading is a new concept introduced with ES6 to make a clone of object/array, in more detail ).

In return, I’ve used an array method called reduce() to get sum of all records of nums (array). and once I have some of my all values, I needed to divide it with a count of record in order to get average and to do that I’ve used num.length to find the length of the array and divided sum with it. Let’s look at some examples of results for better understanding…

Result One:

const result = average(1, 2, 3) // output: 2

Result Two:

const result = average(…[1, 2, 3]) // output: 2

As both results show we have our output value as the average of records we passed in inputs. two ways I’ve mentioned here, the wherein first result I’ve passed all records as individual parameters of a function. While in the second result, I’ve passed an array with spread results. Here, if you are new with term call spreading — check it out here ( it’s video tutorial, very soon I’ll write a detailed post on it too so, stay tuned 😊 ). So, whether you have an array or multi records you can use this function to get an average of it.

Thank you for watching/reading folks, if you found this informative and wanted to make me more content like this please support me on Patreon.

Now, Guys in the next episode I’m going to share a function to get a difference by a function of two arrays. so follow/subscribe to get notification…

Subscribe on youtube https://www.youtube.com/channel/UCvNjso_gPQIPacA6EraoZmg
Facebook: https://www.facebook.com/KatharotiyaRajnish/
Twitter: https://twitter.com/tutorial_spot

Top comments (0)