Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created September 18, 2012 16:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jonathantneal/3743980 to your computer and use it in GitHub Desktop.
Save jonathantneal/3743980 to your computer and use it in GitHub Desktop.
Array.move.js
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;
}
});

Array.move.js

Summary

Moves elements within an array, returning an array containing the moved elements.

Syntax

array.move(index, howMany, toIndex);

Parameters

index: Index at which to move elements. If negative, index will start from the end.

howMany: Number of elements to move from index.

toIndex: Index of the array at which to place the moved elements. If negative, toIndex will start from the end.

Usage

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"]
@slb235
Copy link

slb235 commented Nov 18, 2014

take care, this is not working properly

x = ['a', 'b', 'c']
x.move(0,1,1)

expectet would be

x
Array [ 'b', 'a', 'c' ]

but result ist

x
Array [ 'a', 'b', 'c' ]

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