Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can do this easily using array .sort() & localeCompare() method by passing the {numeric: true} option like:

var unordered = [103,3,4,6,8,"8L",67,1,11,19,68,86,107,"9L"];
var correct = unordered.sort((a,b) => 
  a.toString().localeCompare(b.toString(), undefined, {numeric: true}))
console.log( correct )
.as-console-wrapper { max-height: 100% !important; top: 0; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...