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
132 views
in Technique[技术] by (71.8m points)

javascript: sort an array a certain way with integers and characters

I am trying to sort an array in a specific way and I'm trying to do it efficiently, preferably with the .sort() function. Here is as example of the kind of array I need to work with:

["10", "11", "12", "13", "2", "3", "4", "5", "6", "7", "8", "9", "2a", "2s", "3a"]

Here is what i am looking for after the sort:

["13", "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "3a", "2s", "2", "2a"]

rules:

sort integer values in descending order. integers that have an "a" appended have a lesser value. integers appended with an "s" have a greater value. Therefore, 2a would be inbetween 2 and 1, and 2s would be inbetween 3 and 2. 3a would be greater than 2s.

please help!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Here's a ways to use the javascript .sort() function. Since you want to allow "2a" and "2s", I'm assuming that all input is strings.

Working demo here: http://jsfiddle.net/jfriend00/NDbcC/

var input = ["10", "11", "12", "13", "2", "3", "4", "5", "6", "7", "8", "9", "2a", "2s", "3a"];

var suffix = {"s": 1, "a": -1, 
      "0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 0, 
      "6": 0, "7": 0, "8": 0, "9": 0};

input.sort(function(a, b) {
    var numA = parseInt(a, 10), numB = parseInt(b, 10);
    if (numA == numB) {
        numB = suffix[b.charAt(b.length - 1)];
        numA = suffix[a.charAt(a.length - 1)];
    }
    return(numB - numA);
});

//output is: 
// ["13", "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "3a", "2s", "2", "2a"]

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

...