How to find multiple string items in an array and delete the string that matches the search and return the count of the array?

620 views Asked by At
var stringsToSearch = ["cat", "dog", "rat"];
fromThisArray = ["rabbit", "snake", "cow", "cat", "dog"];

If stringToSearch is found in fromThisArray, It should delete those strings and return the count of the array.

Similar question were asked in this forum but they are finding single string but my requirement was to search multiple string and delete those string.

3

There are 3 answers

2
Jyothi Babu Araja On BEST ANSWER

By using filter and indexOf

var stringsToSearch = ["cat", "dog", "rat"];

var fromThisArray = ["rabbit", "snake", "cow", "cat", "dog"];

var filteredArray = fromThisArray.filter(function(item){
  return stringsToSearch.indexOf(item) < 0;
});

console.log(filteredArray);

0
Aravinder On
var stringsToSearch = ["cat", "dog", "rat"];
var fromThisArray = ["rabbit", "snake", "cow", "cat", "dog"];

for(var i=0; i<stringsToSearch.length; i++){
    var idx = fromThisArray.indexOf(stringsToSearch[i]);
    if(idx > -1){
        fromThisArray.splice(idx, 1);
    }   
}

console.log(fromThisArray, fromThisArray.length);
0
Azad On
function uniqueCount(arr, stringsToSearch ){

  for(var i = 0; i < stringsToSearch.length ; i++){
    while(arr.indexOf(stringsToSearch[i])> -1){
       arr.splice(i,1);//remove
    }
  }
  return arr.length;
}

var stringsToSearch = ["cat", "dog", "rat"];
var fromThisArray = ["rabbit", "snake", "cow", "cat", "dog"];

//call the function 
console.log(uniqueCount(fromThisArray , stringsToSearch ));