Skip to content

Instantly share code, notes, and snippets.

@jfornoff
Created June 23, 2014 06:35
Show Gist options
  • Save jfornoff/db2bb5f0c35bc0364529 to your computer and use it in GitHub Desktop.
Save jfornoff/db2bb5f0c35bc0364529 to your computer and use it in GitHub Desktop.
This is some common element moving functionalitywithin JS Arrays, packaged in a Angular.js factory
app.factory('ArrayService', function(){
return {
deleteElement: function(array, element) {
var index = array.indexOf(element);
if(index == -1){
return false;
}
array.splice(index, 1);
},
moveElementUp: function(array, element) {
var index = array.indexOf(element);
// Item non-existent?
if(index == -1){
return false;
}
// If there is a previous element in sections
if(array[index-1]){
// Swap elements
array.splice(index-1,2,array[index],array[index-1]);
}else{
// Do nothing
return 0;
}
},
moveElementDown: function(array, element) {
var index = array.indexOf(element);
// Item non-existent?
if(index == -1){
return false;
}
// If there is a next element in sections
if(array[index+1]){
// Swap elements
array.splice(index,2,array[index+1],array[index]);
}else{
// Do nothing
return 0;
}
}
}
});
// Just use this within your controllers, don't forget to inject ArrayService into your controller!
// Locates elementWithinArray and deletes it, returns false on error.
ArrayService.deleteElement(myArray, elementWithinArray);
// Swaps elementWithinArray with element before it. Returns false on error.
ArrayService.moveElementUp(myArray, elementWithinArray);
// Swaps elementWithinArray with element after it. Returns false on error.
ArrayService.moveElementDown(myArray, elementWithinArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment