DEV Community

Cover image for Roll Your own One-Line Math.average Function Using Array.reduce
Nick Scialli (he/him)
Nick Scialli (he/him)

Posted on

Roll Your own One-Line Math.average Function Using Array.reduce

Just a quick example of using array.reduce to roll your own one-liner average calculation!

const average = (...nums) => 
  nums.reduce((a, b) => a + b, 0) / nums.length;

console.log(average(1, 2, 3, 4));
// 2.5
Enter fullscreen mode Exit fullscreen mode

Cheers!

Top comments (4)

Collapse
 
maheshthedev profile image
Mahesh Sv •

This might be irrelevant to the topic. but how you made that cover photo with colorful tab design?

Collapse
 
nas5w profile image
Nick Scialli (he/him) •

carbon.now.sh

The theme is Dracula!

Collapse
 
maheshthedev profile image
Mahesh Sv •

thanks

Collapse
 
hycarldev_ profile image
Haikal Azmi •

Might be a stupid question, but if I don't want to put it as average calculation, it's still working right for any calculation?