📜  Lodash _.orderBy() 方法

📅  最后修改于: 2022-05-13 01:56:40.434000             🧑  作者: Mango

Lodash _.orderBy() 方法

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

句法:

_.orderBy(collection, iteratees, orders)

参数:此方法接受三个参数,如上所述,如下所述:

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

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

示例一:这里使用 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。