본문 바로가기
  • 삽질하는 자의 블로그
CS와 언어, 라이브러리 이론/알고리즘-이론과 실전

1. [이론] 자주 쓰는 패턴 총 정리 - 배열편

by 이게뭐당가 2023. 1. 18.

배열

1. 배열의 문자 검색후 인덱스반환 - indexOf, lastIndexOf()

indexOf("string")
indexOf("string", 시작index )

lastIndexOf("string")      		// 뒤에서 부터 검색
lastIndexOf("string", 시작index)  	// num 자리부터 왼쪽으로 검색

	* lastIndexOf 는 뒤의 숫자를 2 라고 하면, index 2 부터 좌측으로 검색한다.

예시

    const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

    console.log(beasts.indexOf('bison'));		// 1
    console.log(beasts.indexOf('bison', 2));	// 4

 

 

2. 배열의 범위지정 - Slice()

slice(start[, end])

    slice() 메서드는 어떤 배열의 begin 부터 end 까지("end 미포함")에 대한 얕은 복사본을 
    새로운 배열 객체로 반환합니다. "원본 배열은 바뀌지 않습니다."
    
    ** end 가 미포함이다.
    ** 원본배열이 바뀌지 않는다.

예시

        const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

        console.log(animals.slice(2));		//  ["camel", "duck", "elephant"]

        console.log(animals.slice(2, 4)); 	// ["camel", "duck"]

        console.log(animals.slice(0, 2)); 	// ['ant', 'bison']

 

 

3. 배열의 교집합, 합집합, 차집합 - filter() & includes()

filter((element) => { /* … */ })
filter((element, index) =>  { /* … */ })

	** index 를 사용하여, 배열의 순환 수를 알 수고 그를 이용할 수 있다.

예시

1. 교집합

    let arrA = [1, 4, 3, 2];
    let arrB = [5, 2, 6, 7, 1];

    arrA.filter(it => arrB.includes(it));	// [1, 2]

2. 합집합

    let arrA = [1, 4, 3, 2];
    let arrB = [5, 2, 6, 7, 1];

    [...new Set([...arrA, ...arrB])];		// [1, 4, 3, 2, 5, 6, 7]

3. 차집합

    let arrA = [1,2,3,4,5]
    let arrB= [2,3,4,6]
    B.filter((item) => !A.includes(item));	// [6]

 

4. 배열 안의 중복된 수 걸러내기 - new Set()

    const arr = [1,1,2,3,3,3,4]
    const set = new Set(arr);               // { 1, 2, 3, 4} 객체화된다.
    const answerArray = [...set];           // [1,2,3,4]

	** 키 값이 없는 객체를, spread 연산자를 사용하여, 배열로 만들기

 

5. 배열의 마지막 배열 자르면서 , 이동시키기 - pop()

 

const arr = [ 1,2,3,4,5]

    arr.pop() = 5
    arr = [1,2,3,4]

 

 

 

배열 순환 ★

1. map() 과 forEach()

만능 순환 아이템들이다.

map 은 새 배열을 반환하고,
forEach 는 그저 순환한다는 차이점이 있다.

    Array.map((value) => value...)
    Array.map((value, index) => value...index...)

예시

 

1. 순환하며, 배열의 범위를 정해놓고 index 검색하기 - map, slice, lastIndexOf

    const Array = ["a", "b", "c", ...]

    Array.map((value, index) => {
            const x = Array.slice(0, index).lastIndexOf(value);
            return x
        }
        
        
1) Array를 순환하며 찾는다.
2) 순환 횟수(index) 에 따라서, 찾으려는 Array의 배열이 변경된다.(slice)
3) 잘린 범위 안에서 value 를 lastIndexOf 로 index 검색을 실시한다.

 

2. 배열 안의 "무엇" 에 대한 중복 횟수 찾기 - forEach

    1) 객체에 값 넣는 방법

        const obj = {}
        obj["key"] = 3
        obj.x = 4

        console.log(obj)    //  key:3 , x:4

    2) forEach 를 사용하여, 값을 넣는다.

        const tanObj = {};
        Array.forEach((t) => (tanObj[t] = (tanObj[t] || 0) + 1));


        ** map 은 새 배열을 반환한다. forEach는 하지 않는다.

 

3. 검색 범위 가 index로 주어질때, [0,3] [2,4]...  map 을 활용해, 순환시키기

map 안에 순환에는 "배열형태" 도 넣을 수 있다

    const square = [ 23, 52, 13, 41]
    const range = [[1, 2],[3, 4], [5,7] ...]

    const x = range.map( ([s,e])=>{		// 순환하는 value 에 "배열 자체" 를 넣어버린다.
        return square.slice(s, e).reduce((a, b) => a + b)	// start, 부터 end 까지 범위를 지정해 squre 를 더한다.
    })

 

댓글