Skip to content
Related Articles

Related Articles

Collect.js last() Method
  • Last Updated : 27 Nov, 2020

The last() method is used to return the last element from the collection that satisfy the given truth test.

Syntax:

collect(array).last(callback)

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

Return Value: This method returns the last element from the collection that satisfy the given truth test.

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



Example 1:




const collect = require('collect.js');
  
const collection = collect([10, 20, 30, 40, 50]);
  
const last_val = collection.last(element => element / 10);
  
console.log(last_val);

Output:

50

Example 2:




const collect = require('collect.js');
  
let obj = [
    {
        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
    },
    {
        name: 'Rahul',
        dob: '19-08-96',
        section: 'B',
        score: 77,
    },
];
  
const collection = collect(obj);
  
const last_val = collection.last(
    element => element.name == 'Rahul');
  
console.log(last_val);

Output:

{ name: 'Rahul', dob: '19-08-96', section: 'B', score: 77 }

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :