1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-09 19:19:07 +01:00
CodeWars/4kyu/remove_zeros/solution.js
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

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