-2

Having this input:

const myArray = ["", "", "test"];

I want to count the number of empty strings, for the above example it is 2. A complicated method would be

myArray.map(a => a.length === 0) which returns a new array of true and false and after that to count them.

Is there a shorter method to do this?

3

3 Answers 3

2

You can filter the undesired values and then check the length of the resulting array:

const emptyCount = myArray.filter(a => a.length === 0).length;
Sign up to request clarification or add additional context in comments.

Comments

2

You could use filter and use length in this way:

const myArray = ["", "", "test"];

let count = myArray.filter(x => x.length === 0).length;

console.log(count);

Comments

1

You can use filter() to get a filtered array with only empty string item. Then you can get the number of item in the array with length.

const myArray = ["", "", "test"];

const output = myArray.filter(el => el === "").length;

console.log(output);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.