-2

Given array :

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];

How to count the number of male in that array ?

Expected result : 3.


Note: I just edited the problem to make it simpler.

5

4 Answers 4

5

Try following

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];

console.log(arr.filter((item) => item.startsWith('male')).length);

Sign up to request clarification or add additional context in comments.

5 Comments

@NinaScholz - Agreeing it to be a better way. Updated. Thanks.
How do you know all the occurrences are at the start of the word? I would instead use String.prototype.includes()
@YosvelQuintero - Makes sense, however, as per the data provided, the above will work well too. Thank you.
Given the number of -1 on my question I'am going to delete this question. Please report your answer to Javascript: search string in array then count occurrences or Count instances of string in an array so I can +1 your elegant answer.
No worries. Thank you for the warning
2
var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
var count=0;
for(var i=0;i<arr.length;i++)
{
if(arr[i].indexOf('male')>-1)
    count++;
}

Comments

2

You can also use regular expressions and the String.prototype.match()

Code:

const arr = ['male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
const count = arr.toString().match(/male/g).length;

console.log(count);

3 Comments

Given the number of -1 on my question I'am going to delete this question. Please report your answer to Javascript: search string in array then count occurrences or Count instances of string in an array so I can +1 your elegant answer.
I have market you question as Favorite and given the +1.. But is ok, you can delete and use the solution on your personal project.. Thanks for the message
I didn't expected my answer to be down voted. Thanks for your code it's indeed the level of elegance I was looking for !
0

You need to iterate upto length of array if string found increment the value of counter. Like following.

var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
var stringCount = 0;
for(var i=0;i<arr.length;i++)
{
   if(arr[i].indexOf('male')>-1){
      stringCount++;
   }
}
console.log(stringCount);

1 Comment

Please refrain from copy pasting other people's answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.