I found this function on the john resig blog for removing an element from an array. It works really well! but I don’t really understand how..
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
I’m confused about what is happening with this statement: (to || from) + 1 || this.length) for starters; perhaps once I understand that, the rest will become more clear. Any help sussing out exactly what’s happening here is much appreciated. Thanks.
The first part gets the rest of the array, after the slice. If you specify a
to, itslices everything after theto; otherwise, itslices everything afterfrom. If either of those were-1, it gets an empty slice.The next part truncates the array to right before the starting position of the removal.
The last part re-inserts the
rest(the part after the range to be removed) at the end of the array.