0

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().

1
  • 3
    How about arr.filter(n => n !== ":" && n !== " ")? Commented Apr 9, 2018 at 22:47

5 Answers 5

4

Chain the conditionals with an AND operator, like this:

arr.filter(n => n !== ":" && n !== " ");
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I feel very silly for not thinking to try that. Thank you!
2

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

Comments

1

Use a regular expression

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

it will match any of the values inside [ and ]

1 Comment

Using the function match is ugly!
1

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

3 Comments

really, can you please explain a bit?
Thanks ele, I changed my answer. Thanks for sharing this thing, I never knew this before. This is the second time I learnt something from you :)
Interesting approach! :)
0
arr = arr.filter(n => n !== ":" && n !== " ");

Pretty simple really! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.