알고리즘 공부3 (map 이용하기 및 구조분해할당)

KHW·2021년 1월 20일
0

알고리즘

목록 보기
3/37

문제

처음 성공한 코드

function solution(array, commands) {
    const commands_length = commands.length;
    let arr = [],answer = [];
    for(let i=0;i<commands_length;i++)
        {
           arr = array.slice(commands[i][0]-1,commands[i][1]);
           arr.sort((a,b)=>a-b);
            answer.push(...[arr.slice(commands[i][2]-1,commands[i][2]]));
        }
    return answer;
}

좀 줄이래서 많이 줄인 코드

function solution(array, commands) {
    return commands.map(x=>array.slice(x[0]-1,x[1]).sort((a,b)=>a-b)[x[2]-1]);
}

commands의 배열이 예를들어 [[2, 5, 3], [4, 4, 1], [1, 7, 3]]라면 map을 이용해 x는 반복할때마다 [ 2, 5, 3 ],[ 4, 4, 1 ],[ 1, 7, 3 ] 총 3번 반복한다. 즉, 처음 반복때 x[0]은 2가 되고 x[1]은 5가되고 x[2]는 3이 된다.

이를 통해 slice를 한 배열을 오름차순으로 정리 한 배열의 x[2]-1 위치가 배열로 리턴된다.

map()

let a = [1,2,3].map(x=>2*x)
console.log(a) // [2,4,6]

배열을 통해 얻어낸 값들을 각각 배열을 통해 다시 넣는다.

구조분해할당

[...[1],...[2],...[3]]  == [1, 2, 3]

ex)

배열.push(배열)를 통해 [[값],[값],[값]] 형태인 경우

let count =[1,2,3,4]
let arr = [];
arr.push(count.slice(1,2));
console.log(arr) // [[2]]

결과가 [2]가아닌 [[2]] 형태이므로 이를 바꿔주기위해서는 2가지 방법이 있는데

  1. 구조분해할당

arr.push(...count.slice(1,2))

  1. flatMap() 사용

한 레벨을 평탄화 시킨다.

let arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

적용 시키기

let count =[1,2,3,4]
let arr = [];
arr.push(count.slice(1,2));
console.log(arr)			//  [[2]]
console.log(arr.flatMap(x=>x))		//  [2]
profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글