Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 25, 2023 03:53 pm GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To