简体   繁体   English

使用JavaScript对数组进行函数排序

[英]Function sort an array with JavaScript

I have to write a function, which sorts an array containing numbers and strings. 我必须编写一个函数,该函数对包含数字和字符串的数组进行排序。
For example: 例如:

uSort([3,"2", 4,1,"a","c","b"])  // -> ["a","b","c",1,"2",3, 4].

This is what I've tried so far: 到目前为止,这是我尝试过的:

function uSort(arrayOfChars){
    var array = [];
    for (i = 0; i < arrayOfChars.length; i++) { 
        if (typeof(arrayOfChars[i]) === '' ){ 
            array.unshift(arrayOfChars[i]); }
        else { 
            array.push(arrayOfChars[i]);
        };   
    }; 
    return array.sort();
};

But the result is wrong: 但是结果是错误的:

uSort([3,"2", 4,1,"a","c","b"])  // -> [1,"2",3, 4,"a","b","c"].

I can't figure out what is wrong with my code right now. 我现在不知道我的代码有什么问题。

One easy way to do that would be to just split the array into two arrays, one containing numbers and strings that are numbers, using isNaN , and one array containing everything else, then sort them and join them back together 一种简单的方法是使用isNaN将数组拆分为两个数组,一个数组包含数字和数字字符串,一个数组包含其他所有内容,然后对它们进行排序并将它们重新连接在一起

function uSort(arrayOfChars){
    var numbs = arrayOfChars.filter(function(item) { return isNaN(item) });
    var chars = arrayOfChars.filter(function(item) { return !isNaN(item) });

    return numbs.sort().concat( chars.sort() );
};

FIDDLE 小提琴

For better sorting of integers and special characters, you can add callbacks to the sorting 为了更好地对整数和特殊字符进行排序,可以将回调添加到排序中

function uSort(arrayOfChars){
    var numbs = arrayOfChars.filter(function(item) { return !isNaN(item) });
    var chars = arrayOfChars.filter(function(item) { return isNaN(item) });

    return chars.sort(function(a, b) {
        return a.localeCompare(b);
    }).concat( numbs.sort(function(a, b) {
        return a == b ? 1 : a - b;
    }));
};

FIDDLE 小提琴

You can use a custom comparator function which checks if the arguments are numeric with isNaN and then uses numerical or lexicographic sort: 您可以使用自定义比较器函数,该函数检查参数是否为带有isNaN数字,然后使用数字或字典排序:

[3, "2", 4, 1, "a", "c", "b"].sort(function(a,b) {
  if(isNaN(a) || isNaN(b)) {
    if(!isNaN(a)) return +1;              // Place numbers after strings
    if(!isNaN(b)) return -1;              // Place strings before numbers
    return a < b ? -1 : (a > b ? +1 : 0); // Sort strings lexicographically
  }
  return a - b;                           // Sort numbers numerically
}); // ["a", "b", "c", 1, "2", 3, 4]

Write your own custom sort method. 编写自己的自定义排序方法。

[3,"2", 4,1,"a","c","b"].sort( function (a,b) { 
    var sa = isNaN(a);
    var sb = isNaN(b);
    if(sa && sb) { //If both are strings, than compare
        return sa>sb; 
    } else if (!sa && !sb) {  //if both are numbers, convert to numbers and compare
        return Number(a) - Number(b);
    } else {  //if we have a number and a string, put the number last.
        return sa ? -1 : 1;
    }
});

It's normal to have numbers before letters (if this is your problem). 通常在字母前加上数字(如果这是您的问题)。

If you want to have letters before you have different ways. 如果您想以不同的方式来信,请先致信。

One way is to order elements into two arrays (one for letters and one for numbers), then to merge them in the order you need. 一种方法是将元素排序为两个数组(一个用于字母,一个用于数字),然后按照需要的顺序合并它们。

Another way is to move the numbers at the end. 另一种方法是将数字移到末尾。

This is an example: alert((uSort([3,"2", 4,10,"a","c","b"]))) // -> ["a","b","c",1,"2",3, 4]. 这是一个示例:alert((uSort([3,“ 2”,4,10,“ a”,“ c”,“ b”]))))//-> [“ a”,“ b”,“ c“,1,” 2“,3,4]。

function uSort(arrayOfChars){
    var arrayNum = [];
    var arrayLet = [];
    for (i = 0; i < arrayOfChars.length; i++) { 
        if (typeof(arrayOfChars[i]) === '' ){ 
            array.unshift(arrayOfChars[i]); }
        else if (typeof(arrayOfChars[i]) === 'number' ){ 
            arrayNum.push(arrayOfChars[i]);
        } else {
            arrayLet.push(arrayOfChars[i]);
        }
    }; 

    if (arrayNum.size!=0 && arrayLet.size!=0) {
        arrayNum = arrayNum.sort(sortNumber);
        arrayNum.push();
        return arrayNum.concat(arrayLet.sort());
    } else if (arrayNum.size!=0) {
        return arrayNum.sort(sortNumber);
    } else {
        return arrayLet.sort();
    }


};

function sortNumber(a,b) {
    return a - b;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM