I want to sort this javascript array:
[103,3,4,6,8,"8L",67,1,11,19,68,86,107,"9L"];
sort it by numbers and letters, so the result will look like this:
[1,3,4,6,8,"8L","9L",11,19,67,68,86,103,107];
When I try to use sort()
, it doesn't work:
[1,3,4,6,8,68,103,"8L",11,19,67,86,107,"9L"]; // 8L and 9L are in the wrong place
// correct wanted order
var correct = [1,3,4,6,8,"8L","9L",11,19,67,68,86,103,107];
document.body.innerHTML += '<b>correct wanted order:</b> <pre>' + JSON.stringify(correct) + '</pre>';
// array to order
var unordered = [103,3,4,6,8,"8L",67,1,11,19,68,86,107,"9L"];
document.body.innerHTML += '<b>array to order:</b> <pre>' + JSON.stringify(unordered) + '</pre>';
unordered = unordered.map(item => {
return item;
});
var ordered = unordered.sort(function(a, b) {
return a - b;
});
document.body.innerHTML += '<b>order attempt:</b> <pre>' + JSON.stringify(ordered) + '</pre>';
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…