Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I move zeros to the end of an array javascript

I want to move the zeros of the array to the end of the array, like

zeroesToEnd([1, 2, 0, 0, 4, 0, 5])

[1, 2, 4, 5, 0, 0, 0]

I’ve tried this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

console.log(zeroesToEnd([1, 2, 0, 0, 4, 0, 5]))

function zeroesToEnd(a) {
    let counter=0;
    let concatarr=[];
    for(let i=0; i <= a.length;i++){
        if(a[i]===0){
            concatarr.push(0);
            counter++
        }
    }
    return a.concat(concatarr)   
}

>Solution :

I would try this, separate the zeros and other numbers then concat them into 1 array

console.log(zeroesToEnd([1, 2, 0, 0, 4, 0, 5]))

function zeroesToEnd(a) {
  let arr1 = a.filter((ele) => ele !== 0)
  let arr2 = a.filter((ele) => ele == 0)
  return arr1.concat(arr2)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading