Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Collect.js reduce() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The reduce() method is used to reduce the collection elements into a single value according to the given callback. It works by passing the result of each iteration to the next one resulting in a single value in the end.

Syntax:

collect(array).reduce(callback)

Parameters: The collect() method takes one argument that is converted into the collection and then reduce() method is applied on it. The reduce() method holds the callback function as parameter.

Return Value: This method returns the reduced value of the collection.

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

Example 1:

Javascript




const collect = require('collect.js');
  
let obj = ['Geeks', 'GFG', 'GeeksforGeeks'];
  
const collection = collect(obj);
  
const total_string_len =
  collection.reduce(
  (str_len, element) => 
    str_len + element.length);
  
console.log(total_string_len);

Output:

21

Example 2:

Javascript




const collect = require('collect.js');
  
let obj = [
    {
        name: 'Rahul',
        marks: 88
    },
    {
        name: 'Aditya',
        marks: 78
    },
    {
        name: 'Abhishek',
        marks: 87
    }
];
  
const collection = collect(obj);
  
const total_name_len =
  collection.reduce(
    (str_len, element) => 
    str_len + element.name.length);
  
console.log(total_name_len);
  
  
const total_marks = collection.reduce(
    (marks, element) =>
     marks + element.marks);
  
console.log(total_marks);

Output:

19
253

My Personal Notes arrow_drop_up
Last Updated : 30 Nov, 2020
Like Article
Save Article
Similar Reads
Related Tutorials