7__Moving Zeros To The End.js 443 B

1234567891011121314151617
  1. //
  2. // Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
  3. // moveZeros([false,1,0,1,2,0,1,3,"a"]) // returns[false,1,1,2,1,3,"a",0,0]
  4. //
  5. var moveZeros = function (arr) {
  6. let arr1 = [];
  7. let arr2 = [];
  8. arr.forEach((el) => {
  9. el === 0 ? arr2.push(el) : arr1.push(el);
  10. });
  11. return [...arr1, ...arr2];
  12. };
  13. moveZeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]);