Alex Rivera | Logout

The best way to remove array element by value

Asked 2011-09-05T16:19:37.133
57

I have an array like this

arr = ["orange","red","black","white"]

I want to augment the array object defining a deleteElem() method which acts like this:

arr2 = arr.deleteElem("red"); // ["orange","black","white"] (with no hole)

What is the best way to accomplish this task using just the value parameter (no index)?

Edit
Report

1 Answer

1

My approach, let's see what others have to say. It supports an "equals" method as well.

 // Remove array value
 // @param {Object} val
 Array.prototype.removeByValue = function (val) {
    for (var i = 0; i < this.length; i++) {
       var c = this[i];
       if (c == val || (val.equals && val.equals(c))) {
          this.splice(i, 1);
          break;
       }
    }
 };

Read https://stackoverflow.com/a/3010848/356726 for the impact on iterations when using prototype with Array.

answered 2011-09-05T16:26:18.437

Your Answer