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.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With