Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptCollect.js average() Method

Collect.js average() Method

The average() method is used to return the average of all the items in a collection. This method is an alias of avg() method.

Syntax:

collect(array).average()

Parameters: The collect() method takes one argument that is converted into the collection and then average() function is applied on it, which can take element if you apply it on the collection of objects.

Return Value: This method returns a number which is average of the collection.

Below example illustrate the average() method in collect.js:

Example 1:

Javascript




const collect = require('collect.js');
  
let arr = [10, 20, 30];
  
let average = collect(arr).average();
  
console.log("Average of the given array: ", average);


Output:

Average of the given array:  20

Example 2:

Javascript




const collect = require('collect.js');
  
let arr = [
    {
        name: 'Rahul',
        score: 98,
    },
    {
        name: 'Aditya',
        score: 96,
    },
    {
        name: 'Abhishek',
        score: 80
    },
];
  
// Converting object to collection 
const collection = collect(arr);
  
// Finding the average of all the score 
let averageScore = collection.average('score');
  
console.log("Average score of students: ", averageScore);


Output:

Average score of students:  91.33333333333333

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments