Home > other >  removing specific items from an array und push them to the end
removing specific items from an array und push them to the end

Time:10-15

i found a javascript exercise in the internet about removing all the zeros from an array and push them to the end of that array. i've found some solutions in the internet but i didn't feel it was straight forward. My solution was :

let arr = [2, 0, 5, 12, 55, 0, 8, 0, 10, 11];
let countItem = 0;

for (let i = 0; i < arr.length; i  ) {
  if (arr[i] === 0) {
    countItem  ;
  }
  if (arr[i] === 0) {
    arr.splice(i, 1);
  }
}

for(j=0; j<countItem;j  ){
    arr.push(0)
}

console.log(arr);

who has an easier approach?

CodePudding user response:

Filter the zeroes then add them all back. You will know how many to add based on the difference in length of the filtered array and original.

const arr = [2, 0, 5, 12, 55, 0, 8, 0, 10, 11];

const notZeroes = arr.filter((n) => n);

const result = notZeroes.concat(Array(arr.length - notZeroes.length).fill(0));

console.log(result);

This is similar to your solution, but removes the need for an extra variable and loop since the counter is already there as the difference in length, and the loop is "built-in" as fill.

CodePudding user response:

You could also use the array filter method:

let arr = [2, 0, 5, 12, 55, 0, 8, 0, 10, 11];

let final_arr = arr.filter(e => e !== 0).concat(arr.filter(e => e === 0));

console.log(final_arr);

So first you filter out the 0 values in the array and concat that array with the an array which only contains the 0 values

  • Related