The sortBy() method is used to sort the collection by the given key.
Syntax:
collect.sortBy()
Parameters: The collect() method takes one argument that is converted into the collection and then sortBy() method is applied on it.
Return Value: This method return the collection after sorting by the given key.
Below example illustrate the sortBy() method in collect.js:
Example 1:
const collect = require('collect.js');     let obj = [     {         subject: 'English',         score: 95,     },    {         subject: 'math',         score: 86,     },     {         subject: 'science',         score: 90,     } ];      const collection = collect(obj);   const sorted = collection.sortBy('score');   let result = sorted.all();         console.log(result); |
Output:
[
{
subject: 'math',
score: 86,
},
{
subject: 'science',
score: 90,
},
{
subject: 'English',
score: 95,
}
]
Example 2:
const collect = require('collect.js');Â Â Â Â Â let obj = [Â Â Â Â Â { product_name: 'apple_laptop', price: 100000 }, Â Â Â Â { product_name: 'apple_watch', price: 50000 }, Â Â Â Â { product_name: 'apple_mobile', price: 80000 }, ]; Â Â Â Â Â const collection = collect(obj);Â Â Â const sorted = collection.sortBy('price'); Â Â let result = sorted.all(); Â Â Â Â Â Â Â Â console.log(result); |
Output:
[
{ product_name: 'apple_watch', price: 50000 },
{ product_name: 'apple_mobile', price: 80000 },
{ product_name: 'apple_laptop', price: 100000 }
]
