使用Lodash按值排序对象数组

时间:2023-01-29 15:58:28

I am trying to sort an array by 'name' value (using Lodash). I used the Lodash docs to create the solution below however .orderBy doesn't seem to be having any affect at all. Can anyone shed some light on the correct way to sort array?

我试图通过'name'值对数组进行排序(使用Lodash)。我使用Lodash文档创建了下面的解决方案。但是,根本没有任何影响。任何人都可以对排序数组的正确方法有所了解吗?

Chars Array

Chars Array

[  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

Function Code

功能代码

 var chars = this.state.characters;

 chars = _.orderBy(chars, 'name', 'asc'); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

2 个解决方案

#1


33  

this method orderBy does not change the input array, you have to assign the result to your array :

此方法orderBy不会更改输入数组,您必须将结果分配给您的数组:

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

#2


14  

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

您可以使用lodash sortBy(https://lodash.com/docs/4.17.4#sortBy)。

Your code could be like:

你的代码可能是这样的:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

#1


33  

this method orderBy does not change the input array, you have to assign the result to your array :

此方法orderBy不会更改输入数组,您必须将结果分配给您的数组:

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

#2


14  

You can use lodash sortBy (https://lodash.com/docs/4.17.4#sortBy).

您可以使用lodash sortBy(https://lodash.com/docs/4.17.4#sortBy)。

Your code could be like:

你的代码可能是这样的:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)