순서 바꾸기

박준혁·2024년 3월 16일


이 문제는 배열을 원하는 요지에 맞게 쪼갤 수 있고 그리고 다시 합칠 수 있는지 여부를 판단하는 문제이다.

  1. n을 기준으로 배열을 쪼갠다 --> slice사용
  2. n의 기준으로 나뉘어진 배열을 각 변수에 넣어준다.
  3. concat을 사용하여 배열을 합친다

내 코드

function solution(num_list, n) {
    let first = num_list.slice(n);
    let after = num_list.slice(0,n);
    console.log(first, after)
    return first.concat(after)
}

메서드 정확히 알고 넘어가기 !

slice사용예시

const num_list = [10, 20, 30, 40, 50];
const n = 3;

const beforeN = num_list.slice(0, n);
console.log(beforeN); // [10, 20, 30]


const afterN = num_list.slice(n);
console.log(afterN); // [40, 50]

const lastTwoElements = num_list.slice(-2);
console.log(lastTwoElements); // [40, 50]

concat은 위의 예시처럼 그냥 쉽게 사용할 수 있다.

다른사람 풀이


function solution(num_list, n) {
    return num_list.slice(n).concat(num_list.slice(0,n));
}

function solution(num_list, n) {
  num_list.unshift(...num_list.splice(n));
  return num_list;
}
profile
"열정"

0개의 댓글