Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

Sort javascript array by numbers and letters

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...