newman
newman

Reputation: 421

Removing multiple array values with Array.filter()

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

Answers (5)

sumit
sumit

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

Ele
Ele

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; }


As academy approach you can join replace and split

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

Jason
Jason

Reputation: 15931

Use a regular expression

arr.filter(n => !n.match(/[:\s]/) );

it will match any of the values inside [ and ]

Upvotes: 1

see sharper
see sharper

Reputation: 12035

arr = arr.filter(n => n !== ":" && n !== " ");

Pretty simple really! :)

Upvotes: 0

Chain the conditionals with an AND operator, like this:

arr.filter(n => n !== ":" && n !== " ");

Upvotes: 4

Related Questions