mirror of
https://gitlab.com/mfocko/CodeWars.git
synced 2024-11-09 11:09:07 +01:00
28 lines
959 B
JavaScript
28 lines
959 B
JavaScript
function swap(array, i, j) {
|
|
let temporary = array[i];
|
|
array[i] = array[j];
|
|
array[j] = temporary;
|
|
}
|
|
|
|
function removeZeros(array) {
|
|
// Sort "array" so that all elements with the value of zero are moved to the
|
|
// end of the array, while the other elements maintain order.
|
|
// [0, 1, 2, 0, 3] --> [1, 2, 3, 0, 0]
|
|
// Zero elements also maintain order in which they occurred.
|
|
// [0, "0", 1, 2, 3] --> [1, 2, 3, 0, "0"]
|
|
|
|
// Do not use any temporary arrays or objects. Additionally, you're not able
|
|
// to use any Array or Object prototype methods such as .shift(), .push(), etc
|
|
|
|
// the correctly sorted array should be returned.
|
|
|
|
for (let i = array.length - 2; i > -1; i--) {
|
|
if (array[i] === 0 || array[i] === '0') {
|
|
for (let j = i; j < array.length - 1 && array[j + 1] !== 0 && array[j + 1] !== '0'; j++) {
|
|
swap(array, j, j + 1);
|
|
}
|
|
}
|
|
}
|
|
|
|
return array;
|
|
}
|