Siwei Shen Siwei Shen - 5 months ago 6
Javascript Question

is it possible to sort an Array in my algorithm using the raw sort() method?

I am wondering if I can sort this Array like this:

[ 0 ,3, 1, 4, 0 ] => [ 1, 3, 4, 0, 0]


detailed rules:


  • the array contains 0 and positive numbers.

  • all the 0 are in the end.

  • all the positive numbers are sorted in ascending order.



At the beginning , I used the js's raw sort function, like:

[0, 3, 1, 4, 0].sort(function(previous_value, former_value){
if(previous_value == 0 && former_value != 0 ) {
return 1;
}else if (former_value == 0 && former_value != 0) {
return -1;
}else if (former_value == 0 && former_value == 0) {
return 0;
}else{
return previous_value - former_value;
}
})


However, I failed. I am wondering if is it possible to implement "my sorting algorithm" using the
sort
function? e.g.:

[0, 3, 1, 4, 0].sort(function(previous_value, former_value){
//code goes here
})


And it will get the correct answer:

[1, 3, 4, 0, 0]

Answer

Give 0 to higher priority

console.log(
  [0, 3, 1, 4, 0].sort(function(a, b) {
    return a === b ? 0 : (a === 0 ? 1 : (b === 0 ? -1 : a - b));
  })
);

With expanded if condition

console.log(
  [0, 3, 1, 4, 0].sort(function(a, b) {
    if (a === b)
      return 0;
    if (a === 0)
      return 1;
    if (b === 0)
      return -1;
    return a - b;
  })
);

Comments