-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?

Jean Pierre
  • 281
  • 8
  • 21
  • 2
    Does this answer your question? [Count instances of string in an array](https://stackoverflow.com/questions/9996727/count-instances-of-string-in-an-array) – Tushar Shahi Jul 07 '21 at 08:46
  • If you can count `true` and `false`, why can't you count the emptystring `""`? – derpirscher Jul 07 '21 at 08:46
  • Check this thread - [How to count certain elements in array?](https://stackoverflow.com/questions/6120931/how-to-count-certain-elements-in-array) – alexnik42 Jul 07 '21 at 08:49

3 Answers3

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);
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
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;
Baboo
  • 4,008
  • 3
  • 18
  • 33
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);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36