Open In App

Collect.js median() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The median() method is used to return the median of the collection elements or median of the given key from the collection.

Syntax:

collect(array).median(key)

Parameters: The collect() method takes one argument that is converted into the collection and then median() method is applied to it. The median() method holds the key as a parameter.

Return Value: This method returns the median of the collection elements.

Module Installation: Install collect.js module using the following command from the root directory of your project:

npm install collect.js

The below example illustrates the median() method in collect.js:

Example 1: Filename: index.js

Javascript




// Requiring the module
const collect = require('collect.js');
  
// Array containing sample values
let arr = [10, 15, -20, -25, 40, 50, -70];
  
// Creating collection object
const collection = collect(arr);
  
// Function call
const median_val = collection.median();
  
// Printing median value
console.log(median_val);


Run the index.js file using the following command:

node index.js

Output:

-25

Example 2: Filename: index.js

Javascript




// Requiring the module
const collect = require('collect.js');
  
// Array containing sample values
let arr = [
  {
      name: 'Rahul',
      dob: '25-10-96',
      section: 'A',
      score: 98,
  },
  {
      name: 'Aditya',
      dob: '25-10-96',
      section: 'B',
      score: 96,
  },
  {
      name: 'Abhishek',
      dob: '16-08-94',
      section: 'A',
      score: 80
  }
];
  
// Creating collection object
const collection = collect(arr);
  
// Function call
const median_val = collection.median('score');
  
// Printing median value
console.log(median_val);


Run the index.js file using the following command:

node index.js

Output:

96


Last Updated : 26 Nov, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads