Home > OS >  Remove all elements in an array that contain a certain character
Remove all elements in an array that contain a certain character

Time:09-11

I have a Javascript array var array = ["1-2", "3-6", "4", "1-6", "4"] and want to remove all elements that contain the variable var m = "6", i.e. "3-6" and "1-6".

I found this line of code var newarray = array.filter(a => a !== "4"), which creates a new array that does not contain the two "4" elements. But I have not found out how to use regular expressions in order to remove all elements that CONTAIN the given variable m = "6".

I thought about something like var newarray = array.filter(a => a !== /eval("return m")/), but this does not work.

I very appreciate your help and apologize for my English :)

CodePudding user response:

string.includes()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

const array = ["1-2", "3-6", "4", "1-6", "4"];

const newarray = array.filter(a => !a.includes("6"))

console.log(newarray);

regex alternative

if you need complex pattern checking, the regex is the way to go.

const array = ["1-2", "3-6", "4", "1-6", "4"];

const newarray = array.filter(a => !a.match(/6/gi))

console.log(newarray);

For example, checking uppercase and lowercase simultaneously, or multiple letters only with [abcde] or some numbers [678] etc...

without nested includes() or logic with if/else.

for learning regex you can use this https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#regular-expressions

another info:

with regex I suggest to add also the g at the end just in case /6/g

g means global (but in this case isn't important, because if there are 6 at least one time. this code will work fine (if you care about multiple 6 then use g)

also use i if you want to select also texts

in fact without i: "A" and "a" aren't the same
so with i you don't have to worry about UPPERCASE or lowercase

you can use both them by doing like this /6/gi

  • Related