우리는 함수를 작성해야 합니다. 예를 들어 숫자 배열을 받아서 가장 큰 요소가 먼저 나타나고 가장 작은 요소가 나타난 다음 두 번째로 큰 요소가 그 다음으로 작은 요소가 오는 식으로 요소를 재배열하는 함수를 작성해야 합니다.
예를 들어 -
// if the input array is: const input = [1, 2, 3, 4, 5, 6, 7] // then the output should be: const output = [7, 1, 6, 2, 5, 3, 4]
따라서 이 함수의 전체 코드를 작성해 보겠습니다.
예시
const input = [1, 2, 3, 4, 5, 6, 7];
const minMax = arr => {
const array = arr.slice();
array.sort((a, b) => a-b);
for(let start = 0; start < array.length; start += 2){
array.splice(start, 0, array.pop());
}
return array;
};
console.log(minMax(input)); 출력
콘솔의 출력은 다음과 같습니다. -
[ 7, 1, 6, 2, 5, 3, 4 ]