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']

1

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.