简体   繁体   English

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

[英]Sort list descending order in JavaScript

Sort the list record in JavaScript in desc order在 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);
}

Current output:电流输出:

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

Now I want to sort above list in descending order looking for output as per below:现在我想按降序对上面的列表进行排序,以查找如下所示的输出:

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
var reversed = dataList.reverse();

You have to use Array.prototype.sort with a comparison function https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort您必须将Array.prototype.sort与比较函数一起使用https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/sort

But I'm not fully understanding your code.但我没有完全理解你的代码。

 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 />"))

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(' '))
}

But still, your approach to the problem is wrong, you should sort values before output.但是,您解决问题的方法仍然是错误的,您应该在输出之前对值进行排序。

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

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

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

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