ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 알고리즘공부 1 _ Js 배열함수 10가지
    이노베이션캠프/알고리즘공부 2023. 6. 21. 20:25

    - 이번에 알고리즘 문제들을 풀며, 배열함수들을 여럿 사용했다. 

    이를 기억하기 위해 드림코딩 유튜브를 토대로 정리 해보려고 한다.

     

    - 정리된 함수

    1 array.join()

    2 array.split()

    3 array.reverse()

    4 array.splice()

    5 array.slice()

    6 array.find()

    7 array.filter()

    8 array.map()

    9 array.some()

    10 array.reduce()

    11 array.sort()

     

    1. array.join()

    - 메서드 / 배열의 모든 요소를 연결해 하나의 문자열로 만듦

    - () 안에 들어있는 걸 배열의 요소 사이에 넣어줌

    let a = ['바람', '비', '불'];
    let myVar1 = a.join();      // myVar1에 '바람,비,불'을 대입
    let myVar2 = a.join(', ');  // myVar2에 '바람, 비, 불'을 대입
    let myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입
    let myVar4 = a.join('');    // myVar4에 '바람비불'을 대입
    
    console.log(a.join()) // 바람, 비, 불
    //새로운 변수 안 만들어줘도 됨

     

    2. split()

    - 메서드 / String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나누어 배열에 넣어줌

    split()
    split(separator)
    split(separator, limit)

    - separator

    : 원본 문자열을 끊어야할 부분을 나타내는 문자열

    : string | RegExp

    - limit

    : 끊어진 문자열의 최대 개수를 나타내는 정수

    : number

    const str = 'The quick brown fox jumps over the lazy dog.';
    
    const words = str.split(' ');
    console.log(words[3]);
    // Expected output: "fox"
    
    const chars = str.split('');
    console.log(chars[8]);
    // Expected output: "k"
    
    const strCopy = str.split();
    console.log(strCopy);
    // Expected output: Array ["The quick brown fox jumps over the lazy dog."]

    3. reverse()

    - 메서드 / 배열의 순서를 반전함

    - 배열 자체를 변환시킴

    const array1 = ['one', 'two', 'three'];
    console.log('array1:', array1);
    // Expected output: "array1:" Array ["one", "two", "three"]
    
    const reversed = array1.reverse();
    console.log('reversed:', reversed);
    // Expected output: "reversed:" Array ["three", "two", "one"]
    
    // Careful: reverse is destructive -- it changes the original array.
    console.log('array1:', array1);
    // Expected output: "array1:" Array ["three", "two", "one"]

    4. splice()

    - 메서드 / 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경

    - 즉, 배열 자체에서 삭제함(원본 배열 바뀜)

     array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

    - start

    : 배열의 변경을 시작할 인덱스, 배열의 길이보다 큰 값이라면 실제 시작 인덱스는 배열의 길이로 설정됨

    음수일 경우 배열의 긑에서부터 요소를 세어나감 (원점 -1, -n이면 끝의 n번째 요소 = array.length -n)

    값의 절대값이 배열의 길이보다 큰 경우 0

     

    - deleteCount

    : 배열에서 제거할 요소의 수

    : 생략하거나 값이 array.length - start 보다 크다면 start부터의 모든 요소를 제거함

    : 0이면 어떤 요소도 제거하지 않음. 이 때는 최소한 하나의 새로운 요소를 지정해야함

     

    - item1, item2, <em>...</em>

    : 배열에 추가할 요소. 아무 요소도 지정하지 않으면 제거만 됨

     

    - 반환값

    : 제거한 요소를 담은 배열

     

    - 제거할 요소의 수와 추가할 요소의 수가 다른 경우 배열의 길이는 달라짐

     

    const months = ['Jan', 'March', 'April', 'June'];
    months.splice(1, 0, 'Feb');
    // Inserts at index 1
    console.log(months);
    // Expected output: Array ["Jan", "Feb", "March", "April", "June"]
    
    months.splice(4, 1, 'May');
    // Replaces 1 element at index 4
    console.log(months);
    // Expected output: Array ["Jan", "Feb", "March", "April", "May"]

     

    5. slice()

    - 메서드 / 어떤 배열의 begin 부터 end 까지(end 미포함)에 대해 얕은 복사본을 새로운 배열 객체로 반환함

    - 원본 배열 바뀌지 않음

        arr.slice([begin[, end]])

    - begin

    : 0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미

    : 음수 인덱스는 배열의 끝에서부터의 길이를 나타냄

    : biegin이 undefined인 경우에는 0번 인덱스부터 slice

    : begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환

     

    - end

    : 추출을 종료할 0 기준 인덱스

    : slice는 end 인덱스를 제외하고 추출함

    : 생략시, 배열의 끝까지 추출

    : 배열의 길이보다 클 시, 배열의 끝까지 추출

     

    - 반환값

    : 추출한 요소를 포함한 새로운 배열

     

    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
    
    console.log(animals.slice(2));
    // Expected output: Array ["camel", "duck", "elephant"]
    
    console.log(animals.slice(2, 4));
    // Expected output: Array ["camel", "duck"]
    
    console.log(animals.slice(1, 5));
    // Expected output: Array ["bison", "camel", "duck", "elephant"]
    
    console.log(animals.slice(-2));
    // Expected output: Array ["duck", "elephant"]
    
    console.log(animals.slice(2, -1));
    // Expected output: Array ["camel", "duck"]
    
    console.log(animals.slice());
    // Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

     

    6. find()

    - 메서드 / 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환함

    - 요소가 없다면 undefined 반환

    arr.find(callback[, thisArg])

    - callback

    : 배열의 각 값에 대해 실행할 함수. 아래의 세 인자를 받음

     

    - element

    : 콜백함수에서 처리할 현재 요소

     

    - index 

    : 콜백함수에서 처리할 현재 요소의 인덱스

     

    - array 

    : find 함수를 호출한 배열

     

    - thisArg

    : 선택 항목. 콜백이 호출될 때 this 로 사용할 객체

     

    - 반환값

    : 주어진 판별 함수를 만족하는 첫 번째 요소의 값. 그 외는 undefined

    const array1 = [5, 12, 8, 130, 44];
    
    const found = array1.find(element => element > 10);
    
    console.log(found);
    // Expected output: 12

     

    7. filter()

    - 메서드 / 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환

    arr.filter(callback(element[, index[, array]])[, thisArg])

    - callback 

    : 각 요소를 시험할 함수. true를 반환하면 요소를 유지하고, false를 반환하면 버림

    : 다음의 세 가지 매개변수를 받음

     

    - element 

    : 처리할 현재 요소

     

    - index

    : 처리할 현재 요소의 인덱스

     

    - thisArg

    : callback을 실행할 때 this로 사용하는 값

     

    - 반환값

    : 테스트를 통과한 요소로 이루어진 새로운 배열. 어떤 요소도 통과하지 못했으면 빈 배열 반환

    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
    
    const result = words.filter(word => word.length > 6);
    
    console.log(result);
    // Expected output: Array ["exuberant", "destruction", "present"]

     

    8. map()

    - 메서드 / 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환함

    arr.map(callback(currentValue[, index[, array]])[, thisArg])

    - callback

    : 새로운 배열 요소를 생성하는 함수. 다음의 세 가지 인수를 가짐

     

    - currentValue

    : 처리할 현재 요소

     

    - index

    : 처리할 현재 요소의 인덱스

     

    - array

    : map()을 호출한 배열

     

    - thisArg

    :callbak을 실행할 때 this로 사용되는 값

     

    - 반환값

    : 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열

    const array1 = [1, 4, 9, 16];
    
    // Pass a function to map
    const map1 = array1.map(x => x * 2);
    
    console.log(map1);
    // Expected output: Array [2, 8, 18, 32]

     

    9. some()

    - 메서드 / 배열 안의 어떤 요소라도 주어진 판별 함수를 적어도 하나라도 통과하는지 테스트함

    - 반환값 : ture / false

    - 배열을 변경하지 않음

    // 화살표 함수
    some((element) => { /* … */ })
    some((element, index) => { /* … */ })
    some((element, index, array) => { /* … */ })
    
    // 콜백 함수
    some(callbackFn)
    some(callbackFn, thisArg)
    
    // 인라인 콜백 함수
    some(function (element) { /* … */ })
    some(function (element, index) { /* … */ })
    some(function (element, index, array) { /* … */ })
    some(function (element, index, array) { /* … */ }, thisArg)

    - callbackFn

    : 배열의 각 요소에 대해 실행할 함수. 이 함수는 요소가 시험을 통과하면 참(같은 값)을 반환하고 아니면 거짓을 반환

    : 다음의 인자와 함께 함수 호출함

     

    - element 

    : 처리할 배열 내 현재 요소

     

    - index

    : 처리할 현재 요소의 인덱스

     

    - array

    : some을 호출한 배열

     

    - thisArg

    : callbackFn을 실행할 때 this로 사용하는 값

     

    - 반환값

    : 콜백함수가 적어도 배열 중 하나의 요소에 대해 참인 값을 반환하면 true

    : 그렇지 않으면 false

     

    const array = [1, 2, 3, 4, 5];
    
    // Checks whether an element is even
    const even = (element) => element % 2 === 0;
    
    console.log(array.some(even));
    // Expected output: true

    * 반대로 전부가 만족하는지 알고 싶으면 array.every() 사용하시길!

     

    10. reduce()

    - 메서드 / 배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환함

    arr.reduce(callback[, initialValue])

    - callback

    : 배열의 각 요소에 대해 실행할 함수. 밑의 네 가지 인수를 받음

     

    - accumulator

    : 콜백의 반환값을 누적함. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 intialValue의 값임

     

    - currentValue

    : 현재 처리할 요소

     

    - currentIndex

    : 처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작함

     

    - initialValue

    : calback 의 최초 호출에서 첫번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용함. 빈 배열에 초기값 없이 reduce()를 호출하면 오류가 발생함

     

    - 반환값

    : 누적 계산의 결과 값

     

    const array1 = [1, 2, 3, 4];
    
    // 0 + 1 + 2 + 3 + 4
    const initialValue = 0;
    const sumWithInitial = array1.reduce(
      (accumulator, currentValue) => accumulator + currentValue,
      initialValue
    );
    
    console.log(sumWithInitial);
    // Expected output: 10

     

    11. sort()

    - 메서드 / 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환함

    - 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따름

    - 정렬 속도와 복잡도는 각 구현방식에 따라 다를 수 있음

     

    arr.sort([compareFunction])

    - compareFunction

    : 정렬 순서를 정의하는 함수

    : 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됨

     

    - 반환값

    : 정렬한 배열

    : 원 배열이 정렬되는 것에 유의. 복사본이 만들어지는 것이 아님

     

    * 숫자를 오름차순으로 정렬하고 싶을 때

    arr.sort((a,b) => a - b)

    * 내림차순은 당연히 반대~

     

    *참고 자료

    https://www.youtube.com/watch?v=3CUjtKJ7PJg 

    각 함수의 MDN 들

Designed by Tistory.