1

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

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)   
}

1 Answer 1

1

I think using the filter method satisfies your question, however in the spirit of keeping the answer in line with your attempt, I wanted to include an answer using for loops.

In my answer, I initialize a variable to keep track of the number of zeros that are in the first array. Then, I initialize a new array that is going to hold the desired results.

I have one for loop stepping through the items in the array passed into the function, and if it is zero I increase the count, otherwise I add the item to the newArray. Afterwards, I have another for loop which runs the number of times we counted for zeros, and adds a zero to the end of the newArray.

Please note this does not mutate the original array, but produces a new array.

function zeroesToEnd(a) {
  let countOfZeros = 0;
  const newArray = [];
  for (const item of a) {
    if (item === 0) countOfZeros++;
    else newArray.push(item);
  }
  for (let i = 0; i < countOfZeros; i++) {
    newArray.push(0);
  }
  return newArray;
}

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.