본문 바로가기
JavaScript

[JavaScript] 배열 고차 함수

by lvd-hy 2023. 3. 17.
반응형

 

목차

     

    배열 고차 함수

    1. Array.prototype.sort

    배열의 요소를 오름차순으로 정렬하는 메서드

    1-1. 문자열 요소 정렬 예시

    const fruits = ['Banana', 'Orange', 'Apple'];
    console.log(months.sort()); // ["Apple", "Banana", "Orange"]
    
    // 내림차순으로 정렬하고 싶다면?
    // reverse 메서드를 사용할 수 있다.
    const fruits = ['Banana', 'Orange', 'Apple'];
    console.log(fruits.sort().reverse()); // ["Orange", "Banana", "Apple"]

    1-2. 숫자 요소 정렬 예시

    const numbers = [1, 2, 10];
    console.log(numbers.sort()); // [1, 10, 2]

    sort 메서드의 기본 정렬 순서는 유니코드 코드 포인트의 순서에 따른다.
    배열의 요소가 숫자 타입이라 할지라도 일시적으로 문자열로 변환한 후 유니코드 코드 포인트의 순서를 기준으로 정렬한다.

    유니코드 코드 포인트 : 유니코드에서 정의한 숫자, 글자 하나에 하나의 포인트를 할당

    Ex
    문자열 '1'의 코드 포인트는 U+0031
    문자열 '2'의 코드 포인트는 U+0032
    문자열 '10'의 코드 포인트는 U+0031+U+0030
    따라서 1, 2, 10 요소의 경우 1, 10, 2으로 정렬이 된다.

    숫자 요소를 오름차순, 내림차순으로 정렬하고 싶다면?

    ➡️ sort 메서드에 정렬 순서를 정의하는 비교함수를 인수로 전달해야한다.

    const numbers = [1, 2, 10];
    
    // 오름차순으로 정렬
    // 비교 함수의 반환값이 0보다 작으면 a를 우선하여 정렬
    console.log(numbers.sort((a, b) => a - b)); // [1, 2, 10]
    
    // 내림차순으로 정렬
    // 비교 함수의 반환값이 0보다 작으면 b를 우선하여 정렬
    console.log(numbers.sort((a, b) => b - a)); // [10, 2, 1]

     

    2. Array.prototype.forEach

    각 배열 요소에 대해 제공된 함수를 한 번씩 실행하는 메서드

    const array1 = [1, 2, 3];
    
    array1.forEach((element) => console.log(element + 2));
    // 3
    // 4
    // 5
    console.log(array1); // [1, 2, 3]

    forEach 메서드는 원본 배열을 변경하지 않는다.

    다만, 콜백 함수를 통해 아래와 같이 원본 배열을 변경할 수 있다.

    const array1 = [1, 2, 3];
    
    // 콜백 함수의 세 번째 매개변수 arr은 원본 배열 array1를 가리킨다.
    // 따라서 콜백 함수의 세 번째 매개변수 arr을 직접 변경하면 원본 배열 array1가 변경된다.
    array1.forEach((item, index, arr) => {arr[index] = item + 2});
    console.log(array1);

    forEach 메서드는 for 문과는 달리 break, countinue문을 사용할 수 없다.
    배열의 모든 요소를 빠짐없이 모두 순회하며 중간에 순회를 중단할 수 없다.

     

    3. Array.prototype.map

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

    const array1 = [1, 4, 9, 16];
    
    const map1 = array1.map((x) => x * 2);
    
    console.log(map1); // [2, 8, 18, 32]

     

    4. Array.prototype.filter

    배열의 모든 요소를 순회하면서 인수로 전달받은 콜백 함수를 반복 호출한다.

    그리고, 콜백 함수의 반환값이 true인 요소로만 구성된 새로운 배열을 반환한다.

    const numbers = [1, 2, 3, 4, 6, 9, 19];
    
    // 홀수인 요소만 필터링하기
    // 1은 true로 평가된다.
    const odd = numbers.filter((num) => num % 2);
    
    console.log(odd); // [1, 3, 9, 19]
    
    //짝수인 요소만 필터링하기
    const even = numbers.filter((num) => num % 2 === 0);
    console.log(even); // [2, 4, 6]

     

    5. Array.prototype.reduce

    배열의 모든 요소를 순회하면서 인수로 전달받은 콜백 함수를 반복 호출한다.

    그리고 콜백 함수의 반환값을 다음 순회 시에 콜백 함수의 첫 번째 인수로 전달하면서 콜백 함수를 호출하여 하나의 결과값을 만들어 반환한다. (원본 배열은 변경하지 않음)

    5-1. 누적값 구하기

    const sum = [1, 2, 3, 4].reduce((accumulator, currentValue, index, array) => accumulator + currentValue, 0);
    
    console.log(sum); // 10

    5-2. 평균 구하기

    const values = [1, 2, 3, 4, 5, 6];
    
    const average = values.reduce((accumulator, currentValue, index, {length}) => {
      // 마지막 순회가 아니면 누적값을 반환하고 마지막 순회면 누적값으로 평균을 구해 반환한다.
      return index === length - 1 ? (accumulator + currentValue) / length : accumulator + currentValue;
    }, 0);
    
    console.log(average); // 3.5

    5-3. 요소의 중복 횟수 구하기

    const fruits = ['banana', 'apple', 'orange', 'apple', 'apple', 'banana'];
    
    const count = fruits.reduce((accumulator, currentValue) => {
      // 첫 번째 순회 시 accumulator는 초기값인 {}이고 currentValue은 첫 번째 요소인 'banana'다
      // 초기값으로 전달받은 빈 객체에 요소값이 currentValue을 프로퍼티 키로, 요소의 개수를 프로퍼티 값으로 할당한다.
      // 만약 프로퍼티 값이 undefined(처음 등장하는 요소)d이면 프로퍼티 값을 1로 초기화한다.
      accumulator[currentValue] = (accumulator[currentValue] || 0) + 1;
      return accumulator;
    }, {});
    
    console.log(count); // { banana: 2, apple: 3, orange: 1 }

     

    6. Array.prototype.find

    배열의 요소를 순회하면서 인수로 전달된 콜백 함수를 호출하여 반환값이 true인 첫 번째 요소를 반환하며, true인 요소가 존재하지 않는다면 undefined를 반환한다. (ES6)

    filter 메서드와 다르게 배열이 아닌 요소를 반환한다.

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

     

    Reference

    자바스크립트 딥다이브 27장.9

    반응형

    댓글