简体   繁体   English

使用数组 sort() 按 ReactJS 中的容量和名称排序

[英]Sort by Capacity and Name in ReactJS using array sort()

I have one question.我有一个问题。 How can I sort array items first by their capacity and then by the first letter of their name?如何先按容量排序数组项,然后按名称的第一个字母排序? The main idea is first to be sorted by capacity from low to high or high to low and then if two items have the same capacity, those two items to be sorted by the first letter of their name.主要思想是首先按容量从低到高或从高到低排序,然后如果两个项目的容量相同,则这两个项目按名称的第一个字母排序。

Here is a basic code sample from me这是我的基本代码示例

myArray.sort((eventA, eventB) => {
      if (this.state.sort.highToLow.enabled) {
         return eventA.capacity > eventB.capacity ? -1 : 1;
     } else if (this.state.sort.lowToHigh.enabled) {
         return eventA.capacity > eventB.capacity ? 1 : -1;
     } else { return 0; }
     })

you can use lodash sortBy method你可以使用 lodash sortBy 方法

_.sortBy(myArray, ['capacity', 'name']);

try some thing like this.尝试这样的事情。 sort method, check for name when capacity is same. sort 方法,当容量相同时检查名称。

 const data = [ { name: "z", capacity: 2, }, { name: "b", capacity: 1, }, { name: "a", capacity: 1, }, ]; data.sort((a, b) => { if (a.capacity === b.capacity) { return a.name > b.name? 1: -1; } return a.capacity - b.capacity; }); console.log(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM