-2

I have an array with strings and I need every element that include a certain string to be deleted.

var arr = ["abc", "123", "dfg", "bbb"];

var string = "b"

After deleting any elements that include the string, the array should look like this:

["123", "dfg"];
Amit
  • 41,690
  • 8
  • 66
  • 101
  • possible duplicate of [Remove item from array by value](http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value) – Meenesh Jain Aug 10 '15 at 05:56

3 Answers3

4

Simple to do with Array.prototype.filter:

var arr = ["abc", "123", "dfg", "bbb"];
var string = "b";

alert(arr.filter(function (i) { return i.indexOf(string) < 0 }))
Amit
  • 41,690
  • 8
  • 66
  • 101
0

You can simply iterate through the array and collect all the items which do not contain the string.
You can use indexOf function to find an occurence of one string into an other.

    var arr = ["abc", "123", "dfg", "bbb"];
    var string = "b";

    var result = [];

    for (var i = 0; i < arr.length; i++)
    {
        if (arr[i].indexOf(string) === -1) 
        {
            result.push(arr[i]);
        }
    }

    document.body.innerHTML = result;

Please, notice, that I have added a document.body.innerHTML = result; line in order to display results. Do not forget to remove it before using in your code :)

Yeldar Kurmangaliyev
  • 30,498
  • 11
  • 53
  • 87
0

You can use Array.prototype.splice method also, Check following snippet.

var arr = ["abc", "123", "dfg", "bbb"];
var string = "b";

arr.splice(1,1);
document.getElementById("ans").value = arr[1];
<input id='ans' type='text'>
chandil03
  • 14,047
  • 5
  • 43
  • 64