【问题标题】:Sort list descending order in JavaScript在 JavaScript 中对列表进行降序排序
【发布时间】:2021-02-03 14:23:53
【问题描述】:

在 JavaScript 中按降序对列表记录进行排序

var number; //here we are getting dynamic number from API

var test; //here we are getting dynamic text from API

for (var i; i <= accList.length; i++) {
  var odlist = 'you have :' + test + number + 

  dataList.push(odlist);
}

当前输出:

1.you have : total 4 accounts of 10

2.you have : total 11 account accounts of 23 

3.you have : total 0 accounts of 100

4. you have : total 2 accounts of 6

现在我想按降序对上面的列表进行排序,以查找如下输出:

1.you have : total 0 accounts of 100

2.you have : total 11 account accounts of 23 

3.you have : total 4 accounts of 10

4.you have : total 2 accounts of 6

【问题讨论】:

    标签: javascript jquery sorting for-loop arraylist


    【解决方案1】:
    var reversed = dataList.reverse();
    

    【讨论】:

      【解决方案2】:
      var tmpArr = []
      for (id in dataList) {
          tmpArr.push(dataList[id].split(' ').reverse())
      }
      tmpArr.sort((a,b) => (a[0] > b[0] ? 1 : -1))
      dataList = []
      for (id in tmpArr) {
          dataList.push(tmpArr[id].reverse().join(' '))
      }
      

      但是,您解决问题的方法仍然是错误的,您应该在输出之前对值进行排序。

      【讨论】:

        【解决方案3】:

        您必须使用Array.prototype.sort 与比较功能 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort

        但我没有完全理解你的代码。

        const dataList = ["1.you have : total 4 accounts of 10",
        "2.you have : total 11 account accounts of 23",
        "3.you have : total 0 accounts of 100",
        "4. you have : total 2 accounts of 6"]
        
        const reg = /(\d+)$/;
        
        dataList.sort((a, b) => {
            const avalue = reg.exec(a)[0]
          const bvalue = reg.exec(b)[0]
            return +bvalue > +avalue
        }).forEach(s => document.write(s + "<br />"))

        【讨论】:

        • Thanks-Romain 但上面的链接不能帮助我解决我的问题。还有其他方法可以对字符串列表进行排序吗?
        • 可以的。我了解您想对字符串中包含的数字进行排序。在比较函数中使用正则表达式来提取数字并对这些值进行排序
        【解决方案4】:
        let dataList = ["teyuwdh 10", "hsdhcksj 100", "euwfhiuweic 1"];
        
        dataList.sort(
            function(a, b) {return b.match(/\d+$/) - a.match(/\d+$/)}
        );
        
        console.log('dataList: ' + JSON.stringify(dataList));
        

        输出:数据列表:["hsdhcksj 100","teyuwdh 10","euwfhiuweic 1"]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-18
          • 2022-01-06
          • 2021-08-09
          • 1970-01-01
          • 2011-07-17
          • 1970-01-01
          • 2023-03-21
          相关资源
          最近更新 更多