# javascript - 按降序對數字進行排序,但開頭應為0

## arrays sorting (7)

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];
let arr1 = arr.filter(item => item === 0);
let arr2 = arr.filter(item => item != 0);

arr2 = arr2.sort();
arr2 = arr2.reverse();

let result = [...arr1, ...arr2]

console.log(result);``````

``let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];``

``arr = [0, 0, 0, 0, 0, 5, 4, 3, 2, 1]``

``````arr.sort((x, y) => {
if (x !== 0) {
return 1;
}

if (x === 0) {
return -1;
}

return y - x;
});``````

``arr = [0, 0, 0, 0, 0, 1, 2, 3, 4, 5]``

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

arr.sort((x, y) => {
return y > x ? 1 : -1;
}).sort((x, y) => {
if (x === 0) { return -1; } return 0;
})``````

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, -1];
arr.sort(function(a, b) {
if (a === 0 && b !== 0) {
// a is zero b is nonzero, a goes first
return -1;
} else if (a !== 0 && b === 0) {
// a is nonzero b is zero, b goes first
return 1;
} else {
// both are zero or both are nonzero, sort descending
return b - a;
}
});
console.log(arr.toString());``````

``````const zeroSort = arr => [...arr.filter(n => n == 0),
...new Float64Array(arr.filter(n => n != 0)).sort().reverse()];

console.log(zeroSort([0, 1, 0, 2, 0, 3, 0, 4, 0, 500]));``````

``Number.MAX_VALUE - Number.MAX_VALUE``

``````let array = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

array.sort((a, b) => (b || Number.MAX_VALUE) - (a || Number.MAX_VALUE));

console.log(...array);``````

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

let result = arr.sort((a,b) => {
if(a == 0 || b == 0)
return a-b;
return b-a;
})
console.log(result)``````

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

let result = arr.sort().sort((a,b) => {
if(a > 0 && b > 0)
return b-a
return 0
})

console.log(result)``````

``````function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}``````

``````let arr = [0, 1, 0, 2, 0, 3, 0, 4, 0, 5];

arr.sort((x, y) => {
if (x > 0 && y > 0) {
return y - x;
}
return x - y;
});

console.log(arr);``````