1252748
1252748

Reputation: 15369

understanding array remove function

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.

Upvotes: 1

Views: 131

Answers (2)

Ry-
Ry-

Reputation: 225074

The first part gets the rest of the array, after the slice. If you specify a to, it slices everything after the to; otherwise, it slices everything after from. 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.

Upvotes: 1

Quentin
Quentin

Reputation: 944011

If the left hand side of || is a true value, it will return the left hand side. Otherwise it will return the right hand side.

Upvotes: 0

Related Questions