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 }