0

I have two arrays and I want to remove items from arr which are in removeStr:

var arr = [ '8','abc','b','c'];

// This array contains strings that needs to be removed from main array
var removeStr = [ 'abc' , '8'];

arr = arr.filter(function(val){
  return (removeStr.indexOf(val) == -1 ? true : false)
})

console.log(arr);

// 'arr' Outputs to :
[ 'b', 'c' ]

But what if I have arrays below:

var arr = [ 'abc / **efg**','hij / klm','**nop** / qrs','**efg** / okl'];

var removeStr = [ 'efg' , 'nop'];

How can I filter elements based on matching string? The result should return:

['hij / klm']

David Walschots
  • 12,279
  • 5
  • 36
  • 59
  • Possible duplicate of [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – rmlan Apr 18 '18 at 16:50

1 Answers1

1

In that case, I think you would need to loop through the removeStr array, and check if each arr element contains the string in the removeStr array.

// var arr = ['8', 'abc', 'b', 'c'];
    // // This array contains strings that needs to be removed from main array
    // var removeStr = ['abc', '8'];

    var arr = ['abc / **efg**', 'hij / klm', '**nop** / qrs', '**efg** / okl'];

    var removeStr = ['efg', 'nop'];

    arr = arr.filter(function (val) {
        var found = false;
        for (var i = 0; i < removeStr.length; i++) {
            var str = removeStr[i];
            if (val.indexOf(str) > -1) {
                return false;
            }
        }
        return true;
    });

    console.log(arr);

    // 'arr' Outputs to :
    ['b', 'c']
Michio
  • 297
  • 2
  • 7