varemenos
4/2/2014 - 12:35 PM

Function to move an Array item to another position of that Array

Function to move an Array item to another position of that Array

var t = [ 'a', 'b', 'c', 'd', 'e'];

Array.prototype.move = function (source, destination) {
	// if source and destination are the same
	if (source === destination) {
		// then there is no need to move
		return;
	}
	// if the source is smaller than 0 or the destination is larger than the size of the array
	if (source < 0 || source > this.length - 1 || destination > this.length - 1) {
		// then the statement is invalid
		throw new RangeError('The \'source\' or \'destination\' parameters are out of range');
	}

	var value2move = this[source];

	this.splice(source, 1);
	this.splice(destination, 0, value2move);
};

t.move(4, 0);

console.log(t);