웹 개발/JavaScript

JavaScript 내장 배열 메소드 한눈에 보기

쫑인스 2021. 11. 8. 23:35

포스팅 목적

배열과 관련된 내장 메소드를 유형별로 분류하여, 사용할 최적의 메소드를 매번 찾기 귀찮아서 찾기 쉽도록  정리했습니다. MDN 홈페이지에 나와있는 메소드를 기준으로 하였습니다. 메소드의 유형이나 중요도는 제가 판단했기 때문에 주관적인 의견이 포함되어 있습니다.

 

유형별 메소드

  • 초기화 : fill, splice
    ( 참고 : 배열 생성시 [ ] ( 리터럴 대괄호 ), new Array() 를 사용 )
  • 요소 추가 / 제거 : pop / push, shift / unshift
  • 정렬 : sort, reverse
  • 순회 : forEach, map, reduce, reduceRight
  • 조건 판단 : every, some, includes, filter
  • 요소 찾기 : find / findIndex, indexOf / lastIndexOf
  • 문자열 반환 : join, toString
  • 새로운 배열 생성 : concat, slice

 

초기화

원본 배열이 수정됩니다.

  • fill() : 배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채웁니다.
    const array1 = [1, 2, 3, 4];
    // fill with 0 from position 2 until position 4
    console.log(array1.fill(0, 2, 4));
    // expected output: [1, 2, 0, 0]​
    Array(3).fill(4); // [4, 4, 4]
  • splice() : 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경합니다.
    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"]​

 

요소 추가 / 제거

원본 배열이 수정됩니다.

  • pop() : 배열에서 마지막 요소를 제거하고 제거된 요소를 반환합니다.
    const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
    console.log(plants.pop());
    // expected output: "tomato"​
  • push() : 배열의 맨 뒤쪽에 요소를 추가하고, 배열의 새로운 길이를 반환합니다.
    const animals = ['pigs', 'goats', 'sheep'];
    const count = animals.push('cows');
    console.log(count);
    // expected output: 4​
  • shift() : 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다.
    const array1 = [1, 2, 3];
    const firstElement = array1.shift();
    console.log(array1);
    // expected output: Array [2, 3]​
  • unshift() : 배열의 맨 앞쪽에 요소를 추가하고, 배열의 새로운 길이를 반환합니다.
    const array1 = [1, 2, 3];
    console.log(array1.unshift(4, 5));
    // expected output: 5​

 

정렬

원본 배열이 수정됩니다.

  • sort() : 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다.
    const array1 = [1, 30, 4, 21, 100000];
    array1.sort(); // 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.
    console.log(array1);
    // expected output: Array [1, 100000, 21, 30, 4]
    
    array1.sort((a, b) => a - b); // 배열을 오름차순으로 정렬합니다.
    console.log(array1);
    // expected output: Array [1, 4, 21, 30, 100000]​
  • 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"]​​

 

순회

콜백 함수에서 원본 배열을 수정하지 않는 한 원본 배열이 수정되지 않습니다.

  • forEach() : 주어진 함수를 배열 요소 각각에 대해 실행합니다.
    const array1 = ['a', 'b', 'c'];
    array1.forEach(element => console.log(element));
    // expected output: "a"
    // expected output: "b"
    // expected output: "c"​
    
    // callback : function(curVal, index, array){ }​
  • map() : 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.
    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]​
    
    // callback : function(curVal, index, array){ }
  • reduce() : 배열의 각 요소에 대해 주어진 reducer 함수를 실행하고, 하나의 결과값을 반환합니다.
    const array1 = [1, 2, 3, 4];
    const reducer = (previousValue, currentValue) => previousValue + currentValue;
    
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15​
    
    // callback  : function(acc, curVal, index, array){ }
  • reduceRight() : reduce 메소드를 오른쪽에서 왼쪽으로 실행하고, 하나의 결과값을 반환합니다.
    const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
      (accumulator, currentValue) => accumulator.concat(currentValue)
    );
    
    console.log(array1);
    // expected output: Array [4, 5, 2, 3, 0, 1]​
    
    // callback  : function(acc, curVal, index, array){ }

 

조건 판단

원본 배열이 수정되지 않습니다.

  • every() : 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 여부를 반환합니다.
    const array = [1, 30, 39, 29, 10, 13];
    array.every((element) => element < 40); // true
  • some() : 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 여부를 반환합니다.
    const array = [1, 30, 39, 29, 10, 13];
    array.some((element) => element < 2); // true
  • includes() : 배열이 특정 요소를 포함하고 있는지 여부를 반환합니다.
    const pets = ['cat', 'dog', 'bat'];
    console.log(pets.includes('cat'));
    // expected output: true
  • filter() : 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열을 반환합니다.
    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"]

 

요소 찾기

원본 배열이 수정되지 않습니다.

  • find() : 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다.
    만족하는 요소가 없으면 undefined를 반환합니다.
    const array1 = [5, 12, 8, 130, 44];
    const found = array1.find(element => element > 10);
    console.log(found);
    // expected output: 12​
  • findIndex() : 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 
    만족하는 요소가 없으면 -1을 반환합니다.
    const array1 = [5, 12, 8, 130, 44];
    const isLargeNumber = (element) => element > 13;
    console.log(array1.findIndex(isLargeNumber));
    // expected output: 3​
  • indexOf() : 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환합니다.
    존재하지 않으면 -1을 반환합니다.
    const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
    
    console.log(beasts.indexOf('bison'));
    // expected output: 1
    
    // start from index 2
    console.log(beasts.indexOf('bison', 2));
    // expected output: 4
    
    console.log(beasts.indexOf('giraffe'));
    // expected output: -1​
  • lastIndexOf() : 배열에서 지정된 요소를 찾을 수 있는 마지막 인덱스를 반환합니다.
    존재하지 않으면 -1을 반환합니다.
    const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
    
    console.log(animals.lastIndexOf('Dodo'));
    // expected output: 3
    
    console.log(animals.lastIndexOf('Tiger'));
    // expected output: 1​

 

문자열 반환

원본 배열이 수정되지 않습니다.

  • join() : 배열의 모든 요소를 연결해 하나의 문자열로 반환합니다.
    const elements = ['Fire', 'Air', 'Water'];
    
    console.log(elements.join());
    // expected output: "Fire,Air,Water"
    
    console.log(elements.join(''));
    // expected output: "FireAirWater"
    
    console.log(elements.join('-'));
    // expected output: "Fire-Air-Water"​
  • toString() : 지정된 배열 및 그 요소를 나타내는 문자열을 반환합니다.
    const array1 = [1, 2, 'a', '1a'];
    
    console.log(array1.toString());
    // expected output: "1,2,a,1a"​

 

새로운 배열 생성

원본 배열이 수정되지 않습니다.

  • concat() : 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다. 
    const array1 = ['a', 'b', 'c'];
    const array2 = ['d', 'e', 'f'];
    const array3 = array1.concat(array2);
    console.log(array1);
    // expected output: Array ["a", "b", "c"]
    console.log(array2);
    // expected output: Array ["d", "e", "f"]
    console.log(array3);
    // expected output: Array ["a", "b", "c", "d", "e", "f"]​
  • slice() : 어떤 배열의 begin부터 end까지(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"]​

 

전체 배열 메소드

더보기

 

참고자료