728x90

Q. 입력받은 string에서 vowels(모음 - a, e, i, o, u)가 몇 개인지 찾아내라.

--- Examples
vowels('Hi There!') --> 3
vowels('Why do you ask?') --> 4
vowels('Why?') --> 0

Code

https://github.com/DasolPark/Algorithm_DataStructure_JavaScript-Stephen-/blob/405d27e61383b84dca83ff1716f9ca74276a2a7f/exercises/vowels/index.js

😢 vowels를 손쉽게 찾도록 도와줄 includes, match를 활용하는 것이 익숙하지 않았다.

😊 Solution 1)
checker array에 모음(a, e, i, o, u)
를 미리 저장해두고, for ... of loop안에서 checker.includes()를 이용해 모음이 있다면 count를 증가시키면서 모음의 개수를 찾아냈다. for ... of는 여러모로 참 유용하다.

Solution 2)
match
helper method안에 RegExp를 삽입하여 매우 간단하게 모음을 찾아냈다.
입력받은 str에 match를 사용해주면, 만약 원하는 값이 match됐을 때, 그 값이 반환된다.
여기서 중요한 것은 RegExp에서 g를 넣어줘야 global로 끝까지 검색을 하여 match된 모든 값의 배열을 반환해주며, i를 넣어줘야 대소문자 구분없이 match를 확인해준다.

✔ Array.prototype.includes()

Array에 있는 값들 중에 includes()괄호 안에 넣어준 값을 포함하고 있나? 확인해준다.

✔ String.prototype.match()

String(문자열)에 있는 character중에 match(RegExp)괄호 안에 있는 RegExp의 조건과 매치되는 값이 있나? 확인해준다.

✔ /[aeiou]/gi

[a, e, i, o, u]중에 하나라도 있으면 체크된다.
g는 global search(한 번 매치되고 끝나지 않고, 끝까지 체크한다)
i는 case-insensitive search 대소문자 구분없이 같은 알파벳이라면 동일하게 체크된다.

Full Code

function vowels(str) {
const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0;
}
 
// function vowels(str) {
// let count = 0;
// const checker = ['a', 'e', 'i', 'o', 'u'];
 
// for (let char of str.toLowerCase()) {
// if (checker.includes(char)) {
// count++;
// }
// }
 
// return count;
// }
728x90

✨ Array에 내가 입력한 값(String or Number etc.)이 포함되어 있는지 확인할 때 사용하는 helper method

(e.g., strArr.includes('a')) 왼쪽처럼 strArr이라는 Array에 'a'가 있다면 true, 없다면 false를 return.
Vowels(모음 찾기) Algorithm에서 유용하게 사용하였다.

 

💻Example Code

const strArr = [ 'a', 'b', 'c' ];

console.log( strArr.includes('a') );

실행 결과( 'a'가 포함되어있기 때문에 true 출력 )

😋 Vowels(모음 찾기) Algorithm을 풀 때, 주어진 String에서 모음(a, e, i, o, u)이 몇 개인지 찾을 때 매우 유용하다.
더 활용된 내용은 Algorithm 카테고리의 Vowels(모음 찾기) Algorithm을 참고하시면 됩니다. 

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.sort()  (0) 2019.12.28
String.prototype.toLowerCase() & toUpperCase()  (0) 2019.12.28
Array.prototype.every()  (0) 2019.12.24
Array.prototype.reduce()  (0) 2019.12.24
Array.prototype.join()  (0) 2019.12.24

+ Recent posts