This content originally appeared on DEV Community and was authored by Muhmmad Awd
DESCRIPTION:
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
Examples
moveZeros([false,1,0,1,2,0,1,3,"a"])
// returns[false,1,1,2,1,3,"a",0,0]
My approach for solving this problem:
- I want to loop throw the array
- when item == 0 I need to remove it from the array then push it to the end of the array
- return the final array
My solution:
const moveZeros =(arr)=> {
for (let i = arr.length - 1; i >= 0; i--) {
if(arr[i] === 0){
arr.splice(i, 1) && arr.push(0);
}
}
return arr
};
I breath with your support, sometimes I feel discouraged when I don't get reactions on my posts. so please Like 👍 & repost 🔄 if you can. Thanks for being here!
Follow Muhmmad Awd on
If you have any questions or feedback, please feel free to contact me at
This content originally appeared on DEV Community and was authored by Muhmmad Awd
Muhmmad Awd | Sciencx (2023-04-25T15:53:33+00:00) Moving Zeros To The End. Retrieved from https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.