inblog logo
|
algorithm-basic
    강의자료

    알고리즘 배열 메서드

    강석우's avatar
    강석우
    Jun 02, 2024
    알고리즘 배열 메서드
    Contents
    Array.prototype.filter()예시요약Array.prototype.map()예시요약Array.prototype.join()예시요약Array.prototype.sort()예시요약Array.prototype.reduce()예시요약

    Array.prototype.filter()

    주어진 배열의 일부에 대한 얕은 복사본을 생성하고, 주어진 배열에서 제공된 함수에 의해 구현된 테스트를 통과한 요소로만 필터링 합니다.

    예시

    예시 1) 모든 작은 값 걸러내기

    10 미만인 요소가 모두 제거된 필터링된 배열을 나타내겠습니다.

    function isBigEnough(value) {
      return value >= 10;
    }
    
    const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
    // 필터링된 값은 [12, 130, 44]

    예시 2) 배열의 모든 소수 찾기

    다음 예제는 배열의 모든 소수를 반환합니다.

    const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
    
    function isPrime(num) {
      for (let i = 2; num > i; i++) {
        if (num % i === 0) {
          return false;
        }
      }
      return num > 1;
    }
    
    console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]

    예시 3) JSON에서 유효하지 않은 항목 걸러내기

    filter()를 사용하여 id가 0이 아닌 숫자인 필터링된 JSON을 생성합니다.
    ( isFinite 메서드는 유한수인지 판별해주는 메서드입니다. )

    const arr = [
      { id: 15 },
      { id: -1 },
      { id: 0 },
      { id: 3 },
      { id: 12.2 },
      {},
      { id: null },
      { id: NaN },
      { id: "undefined" },
    ];
    
    function filterByID(item) {
      if (Number.isFinite(item.id) && item.id !== 0) {
        return true;
      }
      return false;
    }
    
    const arrByID = arr.filter(filterByID);
    
    console.log(arrByID);
    // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]

    예시 4) 배열검색

    검색 조건에 따라 배열 콘텐츠를 필터링합니다.

    const fruits = ["apple", "banana", "grapes", "mango", "orange"];
    
    function filterItems(arr, query) {
      return arr.filter((element) => element.toLowerCase().includes(query.toLowerCase()));
    }
    
    console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
    console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']

    예시 5) 희소 배열에 filter 사용

    console.log([1, , undefined].filter((x) => x === undefined)); // [undefined]
    console.log([1, , undefined].filter((x) => x !== 2)); // [1, undefined]

    요약

    구문

    filter(callbackFn, thisArg)

    매개변수

    callbackFn

    • element

      • 배열에서 처리 중인 현재 요소.

    • index

      • 배열에서 처리 중인 현재 요소의 인덱스.

    • array

      • 호출된 배열

    반환 값

    주어진 배열에서 제공된 함수에 의해 구현된 테스트를 통과한 요소로만 필터링 합니다. 테스트를 통과한 요소가 없으면 빈 배열이 반환됩니다.

    관련 문제

    꼬리 문자열 , 이어 붙인 수

    Array.prototype.map()

    배열 내의 모든 요소에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

    예시

    예시 1) 배열에 들어있는 숫자들의 제곱근을 구하여 새로운 배열을 만들기

    let numbers = [1, 4, 9];
    let roots = numbers.map(Math.sqrt);
    // roots는 [1, 2, 3]
    // numbers는 그대로 [1, 4, 9]

    예시 2) map() 을 활용해 배열 속 객체를 재구성하기

    let myArray = [
      { key: 1, value: 10 },
      { key: 2, value: 20 },
      { key: 3, value: 30 },
    ];
    
    let reformattedArray = myArray.map((value) => {
      let newObject = {};
      newObject[value.key] = value.value; // 대괄호 표기법
      return newObject;
    });

    예시 3) 인자를 받는 함수를 사용하여 숫자 배열 재구성하기

    let numbers = [1, 4, 9];
    let doubles = numbers.map(function (value) {
      return value * 2;
    });

    요약

    구문

    arr.map(callback(currentValue, index, array))

    매개변수

    • currentValue

      • 처리할 현재 요소.

    • index ( Optional )

      • 처리할 현재 요소의 인덱스.

    • array ( Optional )

      • map()을 호출한 배열.

    반환 값

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

    Array.prototype.join()

    배열의 모든 요소를 쉼표나 지정된 구분 문자열로 구분하여 연결한 새 문자열을 만들어 반환합니다.

    예시

    예시 1) 네 가지 다른 방법으로 배열 연결하기

    const a = ["바람", "물", "불"];
    a.join(); // '바람,물,불'
    a.join(", "); // '바람, 물, 불'
    a.join(" + "); // '바람 + 물 + 불'
    a.join(""); // '바람물불'

    요약

    구문

    join(separator)

    매개변수

    • separator

      • 배열의 인접한 요소의 각 쌍을 구분하는 문자열입니다.

    반환값

    배열의 모든 요소들을 연결한 하나의 문자열을 반환합니다.

    관련문제

    문자리스트를 문자열로 변환하기

    Array.prototype.sort()

    배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.
    기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

    예시

    1) 문자열 비교 해보기

    let words = ['jeff','luke','itzel','ian','lay','kevin']
    
    console.log(words.sort());

    2) 문자열 비교가 아닌 숫자 비교를 하는 경우

    문자열 대신 숫자를 비교하기 위해 compare 함수는 a에서 b를 뺄 수 있습니다.

    let numbers = [4, 2, 5, 1, 3];
    numbers.sort(function (a, b) {
      return a - b;
    });
    console.log(numbers);
    
    // [1, 2, 3, 4, 5]

    3) 객체의 속성으로 비교하기 ( 깊게 파보기 )

    let items = [
      { name: "Edward", value: 21 },
      { name: "Sharpe", value: 37 },
      { name: "And", value: 45 },
      { name: "The", value: -12 },
      { name: "Magnetic", value: 13 },
      { name: "Zeros", value: 37 },
    ];
    
    // value 기준으로 정렬
    items.sort(function (a, b) {
      if (a.value > b.value) {
        return 1;
      }
      if (a.value < b.value) {
        return -1;
      }
      // a must be equal to b
      return 0;
    });
    
    // name 기준으로 정렬
    items.sort(function (a, b) {
      let nameA = a.name.toUpperCase(); // ignore upper and lowercase
      let nameB = b.name.toUpperCase(); // ignore upper and lowercase
      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }
    
      // 이름이 같을 경우
      return 0;
    });

    요약

    구문

    arr.sort([compareFunction]);

    매개변수

    • compareFunction

      • 정렬 순서를 정의하는 함수.

      • compareFunction(a, b)이 0보다 작은 경우 a를 b보다 낮은 색인으로 정렬합니다. 즉, a가 먼저옵니다.

      • compareFunction(a, b)이 0을 반환하면 a와 b를 서로에 대해 변경하지 않고 모든 다른 요소에 대해 정렬합니다. ( 이는 보장되지 않습니다. )

      • compareFunction(a, b)이 0보다 큰 경우, b를 a보다 낮은 인덱스로 소트합니다. 즉, b가 먼저 옵니다.

    반환값

    정렬한 배열. 새로운 배열이 아닌 원래의 배열이 정렬됩니다.
    복사본이 만들어지는 것이 아닙니다.

    관련 문제

    문자열 정렬하기 (1)

    Array.prototype.reduce()

    reduce() 메서드는 배열의 각 요소에 대해 주어진 리듀서 (reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.

    예시

    예시 1) 배열의 모든 값의 합산

    var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0);
    // sum is 6

    예시 2) 객체에서 배열의 값 합산

    var initialValue = 0;
    var sum = [{ x: 1 }, { x: 2 }, { x: 3 }].reduce(function (
      accumulator,
      currentValue,
    ) {
      return accumulator + currentValue.x;
    }, initialValue);
    
    console.log(sum); 

    예시 3) 중첩 배열 펼치기

    concat()메서드는 배열을 합치는 역할을 합니다.

    var flattened = [
      [0, 1],
      [2, 3],
      [4, 5],
    ].reduce(function (accumulator, currentValue) {
      return accumulator.concat(currentValue);
    }, []);
    
    // 펼친 결과: [0, 1, 2, 3, 4, 5]

    예시 4) 객체 내의 값 인스턴스 개수 세기

    var names = ["Alice", "Bob", "Tiff", "Bruce", "Alice"];
    
    var countedNames = names.reduce(function (allNames, name) {
      if (name in allNames) {
        allNames[name]++;
      } else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    // countedNames is:
    // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

    요약

    구문

    const testValue = array.reduce(
      (acc, cur) => acc + cur,initialValue,
    );

    매개변수

    • 누산기 (acc)

      • 누산기는 콜백의 반환값을 누적한다. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값입니다.

    • 현재 값 (cur)

      • 처리할 현재 요소.

    • 현재 인덱스 (idx)

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

    • 원본 배열 (src)

      • reduce()를 호출한 배열.

    콜백의 최초 호출 때 accumulator와 currentValue는 다음 두 가지 값 중 하나를 가질 수 있다.
    
    initialValue를 제공한 경우, accumulator는 initialValue와 같고 currentValue는 배열의 첫 번째 값과 같다. 
    
    initialValue를 제공하지 않았다면, accumulator는 배열의 첫 번째 값과 같고 currentValue는 두 번째와 같다.

    반환값

    누적 계산의 결과 값.

    관련 문제

    이어 붙인 수

    Share article
    Contents
    Array.prototype.filter()예시요약Array.prototype.map()예시요약Array.prototype.join()예시요약Array.prototype.sort()예시요약Array.prototype.reduce()예시요약

    algorithm-basic

    RSS·Powered by Inblog