Skip to content

Instantly share code, notes, and snippets.

@albertein
Last active November 28, 2022 11:42
Show Gist options
  • Save albertein/4496103 to your computer and use it in GitHub Desktop.
Save albertein/4496103 to your computer and use it in GitHub Desktop.
Move an element frome an array up or down.
var move = function(array, element, delta) {
var index = array.indexOf(element);
var newIndex = index + delta;
if (newIndex < 0 || newIndex == array.length) return; //Already at the top or bottom.
var indexes = [index, newIndex].sort(); //Sort the indixes
array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]); //Replace from lowest index, two elements, reverting the order
};
var moveUp = function(array, element) {
move(array, element, -1);
};
var moveDown = function(array, element) {
move(array, element, 1);
};
//Test
var array = [1, 2, 3, 4, 5];
moveUp(array, 4);
moveUp(array, 2);
moveDown(array, 5);
@vvelizariy
Copy link

var indexes = [index, newIndex].sort(); //Sort the indixes
Here is the bug, which is based on the fact that default sort acts with indices as strings. So when elements are more than 9, it will place 10 before 9.

@dgcarlin
Copy link

dgcarlin commented Jun 8, 2018

You can correct the bug by using a custom sort function that assumes the indices are numeric, modify line 5 to:
var indexes = [index, newIndex].sort((a, b) => a - b); // or for older javascript use: function(a,b) { return a-b; }

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
moveUp(array, 11); // failed in original version, passes with correction mentioned above.

@bblumenfelder
Copy link

Thanks, you helped me a lot!

@lamaji
Copy link

lamaji commented Dec 5, 2018

Thanks soo much, very helpful.

@NicksonYap
Copy link

A better alternative to move by index directly
(also fixed the issue when moving with index 10)

move(array, index, delta) {
      //ref: https://gist.github.com/albertein/4496103
      console.log('move', array, index, delta);

      var newIndex = index + delta;
      if (newIndex < 0 || newIndex == array.length) return; //Already at the top or bottom.
      var indexes = [index, newIndex].sort((a, b) => a - b); //Sort the indixes (fixed)
      array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]); //Replace from lowest index, two elements, reverting the order
    },

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