11

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.

4 Answers 4

26

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;
});
Sign up to request clarification or add additional context in comments.

Comments

6

Just check the special cases for zero before your other comparisons. So the comparison function might look like this:

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
}

It's vitally important for some sorting algorithms that the comparison function is super consistent, so that's why I've gone to the extra trouble of comparing both are equal at the very beginning.

Comments

4

You could take the delta of falsy values and then sort by value.

console.log([0, 0, 0, 3, 2, 1].sort((a, b) => !a - !b || a - b));

Comments

0
const sortArrByCondition = (arr, func) =>
  arr.sort((oA, oB) => func(oA, oB)? 1: func(oB, oA)? -1 : 0)

sortByCondition (arr, (a, b) => a > b);

sortByCondition works well for string, number and boolean values, as well as more complex functions that return a boolean value.

5 Comments

What is (-1) ** Number(func(a, b)) supposed to achieve? This doesn't work.
Still looks overcomplicated when compared to func(a, b) ? 1 : -1
@Bergi, Sorry about deleting my comment. I wanted to reread your reference. Do you still think it doesn't work? I agree with your latest comment and will adjust my answer accordingly.
Yes, I still think that not returning 0 for equal items is not a good idea
@Bergi I agree. Stability is important for a sorting function. Retrospectively I wouldn't add an answer. But for the sake of the discussion does my edit solve the issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.