Having this array:
const myArry = [1, 543, 0, 232, 1, 45654, -5, 0, 7, 4, 0, 43, 77, 0, 77, 0]
It must be sorted in ascending order and place all 0s at the end, so the output should be:
[-5, 1, 1, 4, 7, 43, 77, 77, 232, 543, 45654, 0, 0, 0, 0, 0]
For sorting it's straightforward:
function sorting(arr) {
for(let i = 0; i< arr.length; i++) {
for (let j = 0; j < arr.length - i -1; j++) {
if(arr[j+1] < arr[j]) {
[arr[j+1], arr[j]]=[arr[j], arr[j+1]];
}
}
}
return arr;
}
But for moving those 0s I cannot find a solution to do it without native functions like push:
function moveZeros(arr) {
let newArray = [];
let counter = 0;
for (let i = 0; i < arr.length; i++) {
if(arr[i] !== 0) {
newArray.push(arr[i]);
}
else { counter++; }
}
for (let j = 0; j < counter; j++) {
newArray.push(0);
}
return newArray;
}
Is there a way to do this? Also, if combining both methods into one