Monday, December 30, 2024
Google search engine
HomeLanguagesJavascriptCollect.js sortBy() Method

Collect.js sortBy() Method

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 }
]

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments