Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array sorting with condition in Javascript

I need to sort an array in ascending order and to put all zeros in the end.

For example [0, 0, 0, 3, 2, 1] needs to be sorted to [1, 2, 3, 0, 0, 0]. This is my code, what do I need to add to make sure all zeros are at the end?

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

Any help will be appreciated.

like image 696
andrey Avatar asked Sep 24 '15 13:09

andrey


1 Answers

You can do something like this:

[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;
});
like image 189
Amir Popovich Avatar answered Sep 22 '22 13:09

Amir Popovich