简体   繁体   中英

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

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

try some thing like this. sort method, check for name when capacity is same.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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