1

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.

7
  • Once you understand how the function has to behave, it's not that hard to see what's going on. The logic behind that line is explained at the bottom of the article, by the way.. Commented Aug 6, 2012 at 15:15
  • And why not use .splice instead? Commented Aug 6, 2012 at 15:21
  • @TimDown Can you suggest another function that does the same, but maybe makes it clearer? Commented Aug 6, 2012 at 15:21
  • @minitech in what way? thanks. Commented Aug 6, 2012 at 15:23
  • @thomas: Array#splice(start, length) does pretty much the same thing. You can also insert elements at the same time. That's what it's for. The only caveat is that it doesn't support negative values for length. Commented Aug 6, 2012 at 15:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.