DEV Community

Mohammed Awad
Mohammed Awad

Posted on

4 1 1 1

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]
Enter fullscreen mode Exit fullscreen mode

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
 };
Enter fullscreen mode Exit fullscreen mode

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

Top comments (2)

Collapse
 
ben profile image
Ben Halpern •

Nice algorithm.

Collapse
 
xmohammedawad profile image
Mohammed Awad •

you are welcome to comment.

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay