Related Articles

Related Articles

Collect.js average() Method
  • Last Updated : 25 Nov, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Average of the given array:  20

Example 2:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

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);

chevron_right


Output:

Average score of students:  91.33333333333333

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :