How do you sort an array on multiple columns?

前端 未结 16 1328
面向向阳花
面向向阳花 2020-11-22 13:02

I have a multidimensional array. The primary array is an array of

[publicationID][publication_name][ownderID][owner_name] 

What I am tryin

16条回答
  •  孤独总比滥情好
    2020-11-22 13:35

    A good way to sort on many fields that are strings is to use toLocaleCompare and the boolean operator ||.

    Something like:

    // Sorting record releases by name and then by title.
    releases.sort((oldRelease, newRelease) => {
      const compareName = oldRelease.name.localeCompare(newRelease.name);
      const compareTitle = oldRelease.title.localeCompare(newRelease.title);
    
      return compareName || compareTitle;
    })
    

    If you wanted to sort on more fields, you could simply chain them off the return statement with more boolean operators.

提交回复
热议问题