📜  Lodash _.sortBy() 方法

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

Lodash _.sortBy() 方法

Lodash 是一个基于 underscore.js 的 JavaScript 库。 Lodash 有助于处理数组、集合、字符串、对象、数字等。

_.sortBy() 方法创建一个元素数组,该数组按通过每个迭代器运行集合中每个元素的结果按升序排序。而且这种方法还执行稳定的排序,这意味着它保留了相等元素的原始排序顺序。

句法:

_.sortBy(collection, iteratees)

参数:此方法接受上面提到的两个参数,如下所述:

  • 集合:此参数保存要迭代的集合。
  • iteratees:此参数保存要排序的迭代对象,并使用一个参数(值)调用。

返回值:该方法用于返回新的排序数组。

示例一:这里使用 const _ = require('lodash') 来导入文件中的 lodash 库。

javascript
// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = [
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 15999 } ];
   
// Use of _.sortBy() method
let gfg = _.sortBy(object, 
    [function(o) { return o.obj; }]);
  
// Printing the output 
console.log(gfg);


javascript
// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = [
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 15999 } ];
   
// Use of _.sortBy() method
let gfg = _.sortBy(object, ['obj', 'price']);
  
// Printing the output 
console.log(gfg);


输出:

[
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'oppo', 'price': 15999 }
]

示例 2:

javascript

// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = [
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 15999 } ];
   
// Use of _.sortBy() method
let gfg = _.sortBy(object, ['obj', 'price']);
  
// Printing the output 
console.log(gfg);

输出:

[
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 15999 },
  { 'obj': 'oppo', 'price': 18999 } 
]

注意:此代码在普通 JavaScript 中不起作用,因为它需要安装库 lodash。