简体   繁体   English

我想以数字方式对字符串进行排序

[英]I would like to sort strings in a numerical manner

I have a sorting function binded with an inverting arrow button for an exam score column我有一个排序 function 与考试分数列的反向箭头按钮绑定

However I can't figure out how to sort them correctly但是我不知道如何正确排序它们

The code below returns下面的代码返回

[N/A, N/A, 99%, 90%, ... 20%, 100%, 10%, 0%] [不适用、不适用、99%、90%、... 20%、100%、10%、0%]

to

[0%, 10%, 100%, 20%, ... 90%, 99%, N/A, N/A] [0%, 10%, 100%, 20%, ... 90%, 99%, 不适用, 不适用]

and vice-versa反之亦然

      // Score Sort
      if(this.scoreSort && this.sortColumn === 'Score'){
        const sortedData = data.sort((a, b) => {
          const titleA = a.Score ? a.Score : '';
          const titleB = b.Score ? b.Score : '';
          if(titleA > titleB){ return this.scoreSort ?  1 : -1 }
          if(titleA < titleB){ return this.scoreSort ? -1 :  1 }
          return 0;
        });
        return sortedData;
      } if(!this.scoreSort && this.sortColumn === 'Score') {
        const sortedData = data.sort((a, b) => {
          const titleA = a.Score ? a.Score : '';
          const titleB = b.Score ? b.Score : '';
          if(titleA > titleB){ return this.scoreSort ?  1 : -1 }
          if(titleA < titleB){ return this.scoreSort ? -1 :  1 }
          return 0;
        });
        return sortedData;
      }

How can I sort them in a manner like the array below?我怎样才能像下面的数组那样对它们进行排序?

[100%, 99%, 90%, ... 20%, 10%, 0%, N/A, N/A] [100%, 99%, 90%, ... 20%, 10%, 0%, 不适用, 不适用]

to

[0%, 10%, 20%, ... 90%, 99%, 100%, N/A, N/A] [0%, 10%, 20%, ... 90%, 99%, 100%, 不适用, 不适用]

and vice versa反之亦然

You could use localeCompare with numeric:true option like this:您可以将localeComparenumeric:true选项一起使用,如下所示:

 const input = ["N/A", "N/A", "99%", "90%", "20%", "100%", "10%", "0%"], sorted = input.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })) console.log(sorted)

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

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