DEV Community

J Mohammed khalif
J Mohammed khalif

Posted on

Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.

Arrays in Javascript are an important data structure alongside objects. As a javascript developer you will use arrays in almost every project that involves grouping/storing data. Arrays are the backbones of javascript data structure, from being able to store any data type to storing arrays inside other arrays i.e multidimensional arrays. We could write about arrays forever and never be out of more words to explain its importance.
To keep it short and precise, lets dive directly to this blogs aim. I love practicing to solve algorithms in and I have seen a question on an algorithm that that takes an array and moves all of the zeros to the end, preserving the order of the other elements. and here is how i solved

function moveZeros(arr) {

//filter out array elements whose values are zero. make sure to use deep comparison operator otherwise false will be refered as a zero, use filter method and this returns a new array of elements with value zero
  let newArr =  arr.filter ( el => el === 0)

//filter out the elements whose values are not zero                    
  let anotherArr = arr.filter (el => el !== 0)

//merge the two arrays using concat method. and to preserve order make sure the array with values zero be passed after the other array
  let finalArr = anotherArr.concat(newArr)

//finally return the final array
return finalArr
}
Enter fullscreen mode Exit fullscreen mode

this can be achieved in one liner but for explanations I decided to keep it longer.
Thanks for reading this blog post. I would personally recommend codewars.

Top comments (0)