Reputation: 421
I have an array of strings:
let arr = ["1", ":", "3", "0", " ", "P", "M"];
I want to remove the ":"
and the whitespace using one filter helper. Is this possible? It works if I chain the methods together.
arr = arr.filter(n => n !== ":").filter(n => n !== " ");
Is there a way that I could run this inside of only one filter method without chaining it? I realize I could also get this done with map()
and run a conditional for string comparisons, but I was curious if it could be done with filter()
.
Upvotes: 0
Views: 58
Reputation: 15464
I will rather do it by making blacklist array
let arr = ["1", ":", "3", "0", " ", "P", "M"],
notAllowed = [' ', ':'];
console.log(arr.filter(a => !notAllowed.includes(a)));
Upvotes: 1
Reputation: 33726
You approach only needs to join the conditions using AND logical operator
arr.filter(n => n !== ":" && n !== " ");
^^
This approach uses the function test
as a handler for the function filter
This is the regex: [:\s]
let arr = ["1", ":", "3", "0", " ", "P", "M"],
result = arr.filter(s => !/[:\s]/.test(s));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Regexp: /[:\s]/g
Assuming the other elements don't have spaces nor colons
let arr = ["1", ":", "3", "0", " ", "P", "M"],
result = arr.join('').replace(/[:\s]/g, '').split('');
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 15931
Use a regular expression
arr.filter(n => !n.match(/[:\s]/) );
it will match any of the values inside [
and ]
Upvotes: 1
Reputation: 12035
arr = arr.filter(n => n !== ":" && n !== " ");
Pretty simple really! :)
Upvotes: 0
Reputation: 11809
Chain the conditionals with an AND operator, like this:
arr.filter(n => n !== ":" && n !== " ");
Upvotes: 4