I often have a list from the server that I need to split into 2 separate arrays. For example, all options that are enabled and all that are not. Here’s a little extension to handle that. Takes a single callback as an argument, with map-style params (value, index, array) – if that iterated callback returns truthy, it’ll be spliced out of the calling array and pushed into the returned array.
Array.prototype.separate = function(callback){ var sep = []; for(var i = 0; i < this.length; i++){ if(callback(this[i], i, this)){ sep.push(this[i]); this.splice(i, 1); i--; } } return sep; }; var letters = ["A", 1, "B", "C", 2, "D", 3, "E"]; var numbers = letters.separate(function(element){ return !isNaN(element); }); alert(letters + "\n" + numbers);
Non-polluting:
function separateArrays(array, callback){ var sep = []; for(var i = 0; i < array.length; i++){ if(callback(array[i], i, array)){ sep.push(array[i]); array.splice(i, 1); i--; } } return sep; };