Sunday, July 11, 2021

Junior Developer Central JS Practice Exercise - 10

 
Question: 

Write a Javascript program to check if a given string contains 2 to 4 occurrences of a specified character. 




Answer: 

function countChar (str, char) {

let arr01 = str.split(''); 
let arr02 = arr01.filter(ch => ch === char).length; 

if (arr02 >= 2 && arr02 <= 4) {
return true; 
} else {
return false;
}
}




> we declare a function 'countChar' 
> it has 2 parameters 'str' & 'char'
> we create a variable 'arr01' & initialize it with a value we get by splitting the 'str' 
> 'arr01' is an array as we have split the 'str' elements into an array of characters
> we create another variable 'arr02' and use the filter method on 'arr01' 
> we want to filter out all the elements that are equal to the character we need to find
> however we do not need an array of all the similar characters 
> we need to know only the number of times it has occurred in the string
> so after using the filter method to find the number of occurrences, we add the length method
> so 'arr02' will be initialized with the number of occurrences
> we then open if/else statements to check two conditions
> if 'arr02' is greater than equal to 2, and if 'arr02' is lesser than equal to 4
> if it is true then we return 'true' 
> if it is false then we return 'false'

No comments:

Post a Comment