当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Lodash _.orderBy()用法及代码示例


Lodash是一个JavaScript库,可在underscore.js顶部使用。 Lodash帮助处理数组,集合,字符串,对象,数字等。_.orderBy()方法与_.sortBy()方法相似,不同之处在于,它允许按迭代顺序对排序进行排序。如果未指定顺序,则所有值均按升序排序,否则相应值的顺序指定“desc”降序或“asc”升序的顺序。

用法:

_.orderBy(collection, iteratees, orders)

参数:此方法接受上述和以下所述的三个参数:

  • collection:此参数保留要迭代的集合。
  • iteratee:此参数保存要排序的迭代对象。
  • order:此参数保存迭代对象的排序顺序。

返回值:此方法返回新的排序数组。

范例1:在这里,const _ = require(‘lodash’)用于将lodash库导入文件中。



// Requiring the lodash library  
const _ = require("lodash");  
       
// Original array  
var users = [ 
  { 'patron':'jonny',   'age':48 }, 
  { 'patron':'john', 'age':34 }, 
  { 'patron':'john',   'age':40 }, 
  { 'patron':'jonny', 'age':36 } 
]; 
   
// Use of _.orderBy() method 
// Sort by `patron` in ascending order 
// and by `age` in descending order 
   
let gfg = _.orderBy(users, ['patron', 'age'],  
             ['asc', 'desc']); 
  
// Printing the output  
console.log(gfg);

输出:

[
  { 'patron':'john',   'age':40 },
  { 'patron':'john', 'age':34 },
  { 'patron':'jonny',   'age':48 },
  { 'patron':'jonny', 'age':36 }
]

范例2:

// Requiring the lodash library  
const _ = require("lodash");  
       
// Original array  
var users = [ 
  { 'employee':'hunny',   'salary':60000 }, 
  { 'employee':'munny', 'salary':40000 }, 
  { 'employee':'hunny',   'salary':55000 }, 
  { 'employee':'munny', 'salary':36000 } 
]; 
   
// Use of _.orderBy() method 
// Sort by `employee` in ascending order 
// and by `salary` in descending order 
   
let gfg = _.orderBy(users, ['employee',  
           'salary'], ['asc', 'desc']); 
  
// Printing the output  
console.log(gfg);

输出:

[
  { 'employee':'hunny',   'salary':60000 },
  { 'employee':'hunny', 'salary':55000 },
  { 'employee':'munny',   'salary':40000 },
  { 'employee':'munny', 'salary':36000 }
]

注意:该代码在常规JavaScript中不起作用,因为它需要安装库lodash。




相关用法


注:本文由纯净天空筛选整理自shivanisinghss2110大神的英文原创作品 Lodash _.orderBy() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。