An Interest In:
Web News this Week
- April 3, 2024
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
April 25, 2023 03:53 pm GMT
Original Link: https://dev.to/muhmmadawd/moving-zeros-to-the-end-5bbo
Moving Zeros To The End
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
Original Link: https://dev.to/muhmmadawd/moving-zeros-to-the-end-5bbo
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To