배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다.
예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면
array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다.
1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다.
2에서 나온 배열의 3번째 숫자는 5입니다.
배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 적용했을 때 나온 결과를 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한사항
array의 길이는 1 이상 100 이하입니다.
array의 각 원소는 1 이상 100 이하입니다.
commands의 길이는 1 이상 50 이하입니다.
commands의 각 원소는 길이가 3입니다.
function solution(array, commands) {
let result = []
for(let i = 0; i < commands.length; i++){
result.push(array.slice(commands[i][0] - 1, commands[i][1]).sort((a,b) => a-b)[commands[i][2] - 1])
}
return result;
}
let a = solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]])
console.log(a);
for문 활용
function solution(array, commands) {
return commands.map(command => {
const [sPosition, ePosition, position] = command
const newArray = array
.filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
.sort((a,b) => a - b)
return newArray[position - 1]
})
}
와우.. 이렇게 활용하는 거구나... 구조분해할당 개념은 알고 있었지만, 활용할 생각을 못했다.
const [sPosition, ePosition, position] = command
let arr = ["Bora", "Lee"]
alert(firstName); // Bora
alert(surname); // Lee
let [a, b, c] = "abc"; // ["a", "b", "c"]
let guest = "Jane";
let admin = "Pete";
// 값을 교환함
[guest, admin] = [admin, guest];
alert(`${guest} ${admin}`); // Pete Jane
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
alert(name1); // Julius
alert(name2); // Caesar
// `rest`는 배열입니다.
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2