Carson Rueter
Carson Rueter

Reputation: 27

How do i find if an array value is in a string and remove it?

I want something like this:

var string = "apple banana";
var array = ["apple", "banana", "orange", "grape"];
for(var i=0;i<array.length;i++){
  if(array[i] is found in (string) {
    remove the value;
  }
}

something like that. so basically, it would:

In case it still doesnt make sense:

String is "1 3 b c"

Array contains "1", "2","3", "a", "b", "c"

The array should now only contain "2" and "a".

Upvotes: 1

Views: 60

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

.filter the array by whether the string does not .includes the substring being iterated over:

const doFilter = (str, arr) => arr.filter(substr => !str.includes(substr));

console.log(
  doFilter("apple banana", ["apple", "banana", "orange", "grape"]),
  doFilter("1 3 b c", ["1", "2","3", "a", "b", "c"]),
);

Upvotes: 2

Related Questions