프로그래머스 1단계 - 나누어 떨어지는 숫자 배열

원동휘·2022년 9월 22일
0

프로그래머스

목록 보기
17/46

< 문제 >

풀이

  • filter메소드를 사용하여 주어진 배열에서 조건에 부합하는(나눴을때 나머지가 0인) 배열을 구하고, 해당배열의 sort문을 이용해 오름차순정렬 진행, 최종결과가 빈배열일 경우에는 문제에 맞게 [-1]로 return
function solution(arr, divisor) {
  const answer = arr.filter(item => item % divisor === 0).sort((a, b) => a - b);
  return answer.length > 0 ? answer : [-1];
}

console.log(solution([5, 9, 7, 10], 5));
console.log(solution([2, 36, 1, 3], 1));
console.log(solution([3, 2, 6], 10));
profile
Front-End Developer #Nextjs #React #Typescript

0개의 댓글