본문 바로가기
알고리즘/Codewars

[Codewars] Friend or Foe? (7 kyu) / JavaScript

by fluss 2022. 10. 31.

https://www.codewars.com/kata/55b42574ff091733d900002f

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Make a program that filters a list of strings and returns a list with only your friends name in it.

If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not...

Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]

i.e.

friend ["Ryan", "Kieran", "Mark"] `shouldBe` ["Ryan", "Mark"]

Note: keep the original order of the names in the output.

 

설명:

문자열 리스트를 걸러서 당신의 친구의 이름만 포함된 리스트를 반환하는 프로그램을 만드세요.

이름이 정확히 4글자라면 당신의 친구라는 것을 확신할 수 있습니다! 그렇지 않다면 그가 아니라는 것을 확신할 수 있습니다...

예: 입력 = ["Ryan", "Kieran", "Jason", "Yous"], 출력 = ["Ryan", "Yous"]

friend ["Ryan", "Kieran", "Mark"] `shouldBe` ["Ryan", "Mark"]

 

참고: 출력에서 이름의 원래 순서를 유지하세요.

 

풀이

filter로 길이가 4글자인 이름만 모은 배열을 반환했다.

 

코드

function friend(friends){
  return friends.filter(word => word.length ===4);
}
 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

 

Array.prototype.filter() - JavaScript | MDN

filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.

developer.mozilla.org

 

댓글