Backdrop

프로그래머스 ▸ 코딩테스트 입문

중앙값 구하기
0

문제 설명

중앙값은 어떤 주어진 값들을 크기의 순서대로 정렬했을 때 가장 중앙에 위치하는 값을 의미합니다. 예를 들어 1, 2, 7, 10, 11의 중앙값은 7입니다. 정수 배열 array가 매개변수로 주어질 때, 중앙값을 return 하도록 solution 함수를 완성해보세요.

제한사항

  • array의 길이는 홀수입니다.
  • 0 < array의 길이 < 100
  • -1,000 < array의 원소 < 1,000

입출력 예

arrayresult
[1, 2, 7, 10, 11]7
[9, -1, 0]0

입출력 예 설명

입출력 예 #1

  • 본문과 동일합니다.

입출력 예 #2

  • 9, -1, 0을 오름차순 정렬하면 -1, 0, 9이고 가장 중앙에 위치하는 값은 0입니다.

풀이

이론

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환해요. 원본 배열은 바뀌지 않아요.

arr.slice([begin[, end]])
  • begin 또는 end 가 음수인 경우, 배열의 끝에서부터의 길이를 나타내요.
  • begin 이 생략된 경우, 0 번째 인덱스부터 추출해요.
  • end 가 생략된 경우, 배열의 끝까지 추출해요.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
 
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
 
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
 
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
 
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
 
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

코드

 

코드

function solution(array) {
  return [...array].sort((a, b) => a - b)[(array.length - 1) / 2];
}