-
-
Save rafaphp/03a72cf9a3f413c0819aa3f48ca27db3 to your computer and use it in GitHub Desktop.
Move an element frome an array up or down.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment