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.
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.
Try following
var arr = [ 'male01', 'woman01', 'male02', 'kid01', 'kid02', 'male06'];
console.log(arr.filter((item) => item.startsWith('male')).length);
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++;
}
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);
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);