Gabriel
Gabriel

Reputation: 43

Remove all matching elements from array

I have this array:

["onelolone", "twololtwo", "three"]

How can I remove the elements using only 'lol' as value and as result be:

["three"]

Upvotes: 2

Views: 710

Answers (2)

customcommander
customcommander

Reputation: 18891

Array#filter is used to keep elements that satisfy a predicate. But we can build a reject function that removes the elements that satisfy a predicate:

const reject = fn => xs => xs.filter(x => fn(x) === false);

Then we can build a curried function for matching a string:

const matches = x => y => y.includes(x);
const reject_lol = reject(matches("lol"));

reject_lol(["onelolone", "twololtwo", "three"]);
//=> ["three"]

We can tweak matches to support any number of strings:

const matches = (...xs) => y => xs.some(x => y.includes(x));
const reject_abbr = reject(matches("lol", "wtf"));

reject_abbr(["lolone", "twowtf", "three"]);
//=> ["three"]

Upvotes: 0

Aplet123
Aplet123

Reputation: 35492

Use Array.prototype.filter, and check that it doesn't include "lol":

const result = ["onelolone","twololtwo","three"].filter(ele => !ele.includes("lol"))

console.log(result)// ["three"]

Upvotes: 6

Related Questions