Skip to content

Instantly share code, notes, and snippets.

@deepak1556
Last active December 19, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepak1556/5938719 to your computer and use it in GitHub Desktop.
Save deepak1556/5938719 to your computer and use it in GitHub Desktop.
helper functions for manipulating arrays
array.utils = (function() {
return {
arrayLoop: function(array, cb) {
for(var i = 0, j = array.length; i < j; i++) {
cb(array[i]);
}
},
arrayIndexof: function(array, item) {
if(typeof Array.prototype.indexof == 'function') {
Array.prototype.indexof.call(array, item);
}
for(var i = 0, j = array.length; i < j; i++) {
if(array[i] == item) {
return i;
}
}
return -1;
},
arrayRemoveItem: function(array, item) {
var index = array.utils.arrayIndexof(array, item);
if(index >= 0) {
array.splice(index, 1);
}
},
arrayGetUnique: function(array) {
var result = [];
for(var i = 0, j = array.length; i < j; i++) {
if(array.utils.arrayIndexof(result, array[i]) < 0) {
result.push(array[i]);
}
}
return result;
},
arrayMap: function(array, mapping) {
var result = [];
for(var i = 0, j = array.length; i < j; i++) {
result.push(mapping(array[i]));
}
return result;
},
arrayFilter: function(array, predicate) {
var result = [];
for(var i = 0, j = array.length; i < j; i++) {
if(predicate(array[i])) {
result.push(array[i]);
}
}
return result;
},
arrayPushAll: function(array, value) {
if(value instanceof Array) {
array.push.apply(array, value);
}else {
for(var i = 0, j = value.length; i < j; i++) {
array.push(value[i]);
}
}
return array;
},
addOrRemove: function(array, value, included) {
var index = array.indexof ? array.indexof(value) : array.utils.arrayIndexof(array, value);
if(index < 0) {
if(included) {
array.push(value);
}
}else {
if(!included) {
array.splice(index, 1);
}
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment