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]


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Moving Zeros To The End." Muhmmad Awd | Sciencx - Tuesday April 25, 2023, https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/
HARVARD
Muhmmad Awd | Sciencx Tuesday April 25, 2023 » Moving Zeros To The End., viewed ,<https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/>
VANCOUVER
Muhmmad Awd | Sciencx - » Moving Zeros To The End. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/
CHICAGO
" » Moving Zeros To The End." Muhmmad Awd | Sciencx - Accessed . https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/
IEEE
" » Moving Zeros To The End." Muhmmad Awd | Sciencx [Online]. Available: https://www.scien.cx/2023/04/25/moving-zeros-to-the-end/. [Accessed: ]
rf:citation
» Moving Zeros To The End | Muhmmad Awd | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.