Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move zeroes in array using ES6 features

I’m new to ES6, trying to make a function that moves all zeros in the array in the last position of the array while preserving the original order of the array E.g. [1,0,0,0,2,3,4,5] => [1,2,3,4,5,0,0,0]

 function moveZeros (arr) {
  let zeroArr = [];
    for(let i = 0;i < arr.length;i++) {
    if (arr[i] == 0) {
     zeroArr.push(arr[i]);
     arr.splice(i, 1);
    }
  }
  arr.push(...zeroArr);
  return arr;
} 

This is my code its works fine, but I think this can be shorter more in using some ES6 features. Can someone provide a better solution

like image 482
shen Avatar asked Dec 05 '22 10:12

shen


2 Answers

That can be solved easily using filter function and spread operator, .

const moveZeros = arr => {
  const z = arr.filter(a => a === 0); // get all zeroes
  const nZ = arr.filter(a => a !== 0); // get all non zeroes
  return [...nZ, ...z]; // put the zeroes on the last position
};
like image 174
onecompileman Avatar answered Dec 24 '22 11:12

onecompileman


As requested in comments: what about sort?

arr.sort((a, b) => -!b)

It is for sure less performant, but hella shorter

Old

Onecompileman got an ok solution, but as OP wanted 'shorter' solution, i think we can reduce some unnecessary parts:

const moveZeros = a => [...a.filter(x => !!x), ...a.filter(x => !x)]
like image 42
lucifer63 Avatar answered Dec 24 '22 12:12

lucifer63