알고리즘 | codewars | list filtering

GEUNNN Lee·2021년 6월 5일
0

알고리즘

목록 보기
2/3

codewars 라는 플랫폼에서 알고리즘을 풀어보기로 정하고 새 플랫폼에서 시작해보려고 한다.

In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

배열에서 string과 숫자가 주어진 배열에서 string만 제외한 숫자만 포함된 새 배열을 리턴하는 문제이다.

내 풀이

function filter_list(l) {
  // Return a new array with the strings filtered out
  for (let i = 0; i<l.length; i++) {
    if (typeof(l[i]) === "string") {
      l.splice(i,1)
      i--;
    }
  }
    return l
}

배열에 filter 메소드가 있다는걸 찾아보지 않고 그냥 반복문으로 돌려서 풀었다.

모범 답안

function filter_list(l) {
  return l.filter(function(v) {return typeof v == 'number'})
}

filter 메소드를 활용하면 길었던 코드가 한 줄로 줄어든다. 화살표 함수를 사용하여 같은 함수를 다시 쓸 수도 있다.


배열 메소드를 잘 활용해서 어떻게 코드를 줄일 수 있는지도 고민해봐야겠다.

profile
Frontend Developer 👩🏻‍💻👩‍💻

0개의 댓글