issue #192 of rendezvous with cassidoo

Given an integer array, move all 0s to the end of it while maintaining the relative order of the non-zeroes

by Jesse Rogers

JavaScript

/* Given an integer array, move all 0s to the end of it while maintaining the relative order of the non-zeroes. Bonus: do this without making a copy of the array! */

Array.prototype.moveZeros = function() {
	for (let i = this.length - 1; i >= 0; i--) {
  	if (typeof this[i] !== 'number') {
    	throw new Error('Array.moveZeros requires type of "number"')
    }
  	if (this[i] === 0) {
    	this.push(...this.splice(i, 1))
    }
  }
}

const data = [0,2,0,3,8]
data.moveZeros()
console.log(data)