Array.move.js – JavaScript for moving element on array

Lebih mudah jika kita menginginkan untuk sorting suatu element di dalam array baik accending atau decending.
Lain perkara kalau kita diharuskan memindah-mindahkan element array itu tanpa adanya Rule yang jelas alias custom.
Nah untuk hal ini saya menggunakan function yang telah dengan baik dibuatkan oleh jonathantneal, yakni Array.move.js

Dengan ini sangat mudah memindahkan element array secara custom.

Array.prototype.move || Object.defineProperty(Array.prototype, "move", {
	value: function (index, howMany, toIndex) {
		var
		array = this,
		index = parseInt(index) || 0,
		index = index < 0 ? array.length + index : index,
		toIndex = parseInt(toIndex) || 0,
		toIndex = toIndex < 0 ? array.length + toIndex : toIndex,
		toIndex = toIndex <= index ? toIndex : toIndex <= index + howMany ? index : toIndex - howMany,
		moved;
 
		array.splice.apply(array, [toIndex, 0].concat(moved = array.splice(index, howMany)));
 
		return moved;
	}
});

Cara menggunakannya sangat mudah, cukup dengan syntax :

array.move(index, howMany, toIndex);

Contoh penggunaan :

array = ["a", "b", "c", "d", "e", "f", "g"];
array.move(3, 2, 1); // returns ["d","e"]
array; // returns ["a", "d", "e", "b", "c", "f", "g"]

mazipan-signature

Be a good reader, leave your comment please.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s