在JavaScript中按列表降序排序



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

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

您必须将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 />"))

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"]

最新更新