0

Yesterday I put the following question:

The best way to remove array element by value

Actually the solution found is not valid because.

Let's suppose this use case:

Array.prototype.deleteElem = function(val) {
   var index = this.indexOf(val); 
   if (index >= 0) 
        this.splice(index, 1);
   return this;
}; 

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

As you can see this method delets just one entry, and not all of them equal to "red". How can I fix it? Maybe with recursion?

Community
  • 1
  • 1
antonjs
  • 14,060
  • 14
  • 65
  • 91
  • If the accepted answer to [your previous question](http://stackoverflow.com/questions/7310559/the-best-way-to-remove-array-element-by-value/7310618#7310618) isn't valid, then uncheck the selected answer, clarify the question and leave a comment for someone indicating the issue. – user113716 Sep 06 '11 at 15:12
  • [This answer](http://stackoverflow.com/questions/7310559/the-best-way-to-remove-array-element-by-value/7310691#7310691) from [@Šime Vidas](http://stackoverflow.com/users/425275/sime-vidas) will work for you if you just remove the `return` statement. – user113716 Sep 06 '11 at 15:14

1 Answers1

1

Using looping works just as well:

Array.prototype.deleteElem = function (val) {
    var index;

    while ((index = this.indexOf(val)) !== -1) {
        this.splice(index, 1);
    }
};

If you have access to the latest version of JavaScript (present in IE>=9 and modern browsers, or shimmed with es5-shim), you can get a new array containing all but that element like so:

var withoutValue = myArray.filter(function (el) { return el !== value; });
Domenic
  • 110,262
  • 41
  • 219
  • 271