Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter Array of Strings by Array of Strings allowing partial matches

I have strings in an array and need to remove entries that contain strings. But also removing partial matches.

var rawData = ["foo", "bar", "foobar", "barbaz", "boo" ]
var unwantedData = ["foo","baz"]
var cleanData = filter(rawData,unwantedData)
console.log(cleanData)
>>>["bar","boo"]

My current solution is as follows:

function filter(data,filterArray){
  return data.filter(rawEntry => {
    var t = true; // set to false if index is found
    filterArray.forEach(unwantedStr => { t = t && ~rawEntry.indexOf(unwantedStr) ? false : t });
    return t; //decides if entry gets removed by filter
  });
}

But i feel like there might be a nicer way to do it. This is probably computationally not the most efficient way.

like image 479
Timar Ivo Batis Avatar asked Jan 27 '23 04:01

Timar Ivo Batis


2 Answers

You can .filter() using .every() and .includes() methods.

let rawData      = ["foo", "bar", "foobar", "barbaz", "boo"],    
    unwantedData = ["foo", "baz"];

let filterData = (a1, a2) => a1.filter(s => a2.every(v => !s.includes(v)));

console.log(filterData(rawData, unwantedData));
like image 166
Mohammad Usman Avatar answered Jan 31 '23 21:01

Mohammad Usman


Beside the use of Array#every, you could do the same by inversing the logic and use Array#some.

var rawData = ["foo", "bar", "foobar", "barbaz", "boo"],
    unwantedData = ["foo", "baz"],
    result = rawData.filter(s => !unwantedData.some(t => s.includes(t)));

console.log(result);
like image 24
Nina Scholz Avatar answered Jan 31 '23 22:01

Nina Scholz