Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created May 17, 2019 18:31
Show Gist options
  • Save jasonwaters/442b0016df0b3112d020dd2384ddc5d3 to your computer and use it in GitHub Desktop.
Save jasonwaters/442b0016df0b3112d020dd2384ddc5d3 to your computer and use it in GitHub Desktop.
Move non-zeroes to the left of an array.
const a = [2,3,0,0,0,0,0,2,3,4,0,2,0,3,0,1,8];
function leftify(arr) {
let leftmost = 0;
arr.forEach((el, idx) => {
if(el !== 0) {
const elements = arr.splice(idx,1);
arr.splice(leftmost,0,...elements);
leftmost++;
}
})
return arr;
}
console.log(leftify(a));
@jasonwaters
Copy link
Author

function leftify_a(arr) {
  let left = 0;
  let tmp
  arr.forEach((value, idx) => {
    if(value !== 0) {
      tmp = arr[left];
      arr[left] = value;
      arr[idx] = tmp;
      left++;
    }
  });
  return arr;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment