在Javascript中使用条件排序数组

and*_*rey 5 javascript arrays sorting

我需要按升序对数组进行排序,并将所有零都放在最后.

例如,[0,0,0,3,2,1]需要排序为[1,2,3,0,0,0].这是我的代码,我需要添加什么来确保所有零都在最后?

function sort_by_field(array, field){
                return array.sort(function(a, b){
                    if( a[field] > b[field] ){
                        return 1;
                    }
                    if( a[field] < b[field] ){
                        return -1;
                    }
                    return 0;
                });
            }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Ami*_*ich 15

你可以这样做:

[0, 0, 0, 3, 2, 1].sort(function(a,b){ 
    if(a === 0) return 1;
    else if(b === 0) return -1;
    else return a - b;
});
Run Code Online (Sandbox Code Playgroud)


rya*_*uyu 5

在进行其他比较之前,只需检查零的特殊情况。所以比较函数可能如下所示:

function(a, b) {
    if (a === b)
        return 0;
    if (a === 0)
        return 1;
    else if (b === 0)
        return -1;

    //the rest of the comparison logic
}
Run Code Online (Sandbox Code Playgroud)

对于某些排序算法来说,非常重要的是比较函数是超级一致的,这就是为什么我一开始就比较麻烦地比较两者是否相等。