Camilla
young Camilla
Camilla
  • 전체보기 (90)
    • Data Analysis (1)
    • SAP (5)
      • SAP Datasphere (0)
      • SAP HANA DB (1)
      • SAP Analytics Cloud (0)
      • SAP BW (4)
    • Web (51)
      • JavaScript (8)
      • React (10)
      • WebRTC (3)
      • node.js (7)
      • Vue (2)
      • CSS (2)
      • 기타 (19)
    • CS (13)
      • Network (8)
      • OS (5)
    • 기타 (2)
      • Git (1)
      • Unity (1)
    • 알고리즘 문제 풀이 (11)
      • 백준 (9)
      • 프로그래머스 (2)
    • 회고 (6)
    • 취준 (0)

More

  • 방명록
  • Github

태그

  • 리액트
  • fontawsome
  • 리액트채팅
  • JavaScript
  • 리액트아이콘
  • 리액트프로젝트
  • fontawsome리액트
  • 채팅기능구현
  • fontawsomereact

최근 댓글

인기 글

티스토리

hELLO · Designed By 정상우.
Camilla

young Camilla

자바스크립트 자주 쓰는 Array 내장 함수들
Web/JavaScript

자바스크립트 자주 쓰는 Array 내장 함수들

2022. 6. 4. 23:31

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/Indexed_collections#배열_객체의_메서드

Array 내장 함수들

 

forEach (callback )

배열의 모든 요소에 대해 반복적으로 주어진 callback을 실행.

var a = ['a', 'b', 'c'];
a.forEach(function(element) { console.log(element);} );
// logs each item in turn
arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

  • 콜백 안에서 사용할 this를 정해줄 수도 있음.
  • forEach()는 각 배열의 요소에 대해 한번씩 콜백함수를 실행한다. map()과 reduce()와는 달리 undefined를 반환하기 때문에 메서드 체인의 중간에는 사용할 수 없다.
  • 대표적으로는 메서드 체인 끝에 반환된 배열에 대한 조작을 할 때 forEach()를 사용하곤 한다.
  • forEach()자체는 배열을 변형하지 않는다. 그러나 주어진 callback이 배열을 변화시킬 수는 있다.
  • forEach()는 예외를 던지지 않고 중간에 멈출 수 없음. 따라서 중간에 멈춰야 한다면 forEach가 적절한 방법이 아닐 수도 있다. 중간에 멈춰야 한다면 다음과 같은 방법들을 쓰는 것이 적절하다.
    • 간단한 for 반복문
    • for ... of, for...in(object일때) 반복문
    • every(),some(),find(),findIndex()

map(callback)

배열의 모든 요소에 대해 콜백 함수를 실행하고 결과를 새로운 배열에 담아 반환.

var a1 = ['a', 'b', 'c'];
var a2 = a1.map(function(item) { return item.toUpperCase(); });
console.log(a2); // logs ['A', 'B', 'C']
arr.map(callback(currentValue[, index[, array]])[, thisArg])
  • 콜백함수에서 사용할 this값을 정해 줄 수 있음.
  • map()은 원본 배열을 변경하지 않지만, 실행되는 콜백이 변경시킬 수 있음.
  • map()을 호출한 배열 중간이 비어있다면, 결과 배열 또한 동일한 인덱스를 빈 값으로 유지한다.

filter (callback)

배열의 모든 요소에 대해 콜백 함수가 true를 반환하는 요소를 새로운 배열에 담아 반환

var a1 = ['a', 10, 'b', 20, 'c', 30];
var a2 = a1.filter(function(item) { return typeof item == 'number'; });
console.log(a2); // logs ['10', '20', '30']

every(callback)

배열의 모든 항목에 대해 true 이면 true반환

function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.every(isNumber)); // logs false

some(callback)

배열의 모든 요소에 대해 콜배함수를 실행하고 하나의 요소라도 콜백함수의 결과가 true라면 true반환

function isNumber(value){
  return typeof value == 'number';
}
var a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // logs true
var a2 = [1, '2', 3];
console.log(a2.some(isNumber)); // logs true
var a3 = ['1', '2', '3'];
console.log(a3.some(isNumber)); // logs false

reduce(callback)

배열 요소를 하나로 줄이기 위해 firstValue, secondValue를 인자로 받는 콜백함수

var a = [10, 20, 30];
var total = a.reduce(function(first, second) { return first + second; }, 0);
console.log(total) // Prints 60

재귀적으로 하나의 시퀀스를 하나의 값으로 질이기 위해 두개의 값을 합치는 알고리즘을 위해 사용 되어야 한다.

concat()

두개의 배열을 합쳐 새로운 배열 반환

var myArray = new Array('1', '2', '3');
myArray = myArray.concat('a', 'b', 'c');
// myArray is now ["1", "2", "3", "a", "b", "c"]

join(delimiter=’,’)

배열의 모든 요소를 구분자로 연결된 하나의 문자열을 반환.

var myArray = new Array('Wind', 'Rain', 'Fire');
var list = myArray.join(' - '); // list is "Wind - Rain - Fire"

push()

하나 혹은 그 이상의 요소를 배열의 마지막에 추가하고 추가된 요소를 포함한 길이를 반환

var myArray = new Array('1', '2');
myArray.push('3'); // myArray is now ["1", "2", "3"]

pop()

배열의 마지막 요소를 제거하고 그 제거된 요소를 반환

var myArray = new Array('1', '2', '3');
var last = myArray.pop();
// myArray is now ["1", "2"], last = "3"

slice(start_idx, upto_idx)

배열의 특정 부분을 추출하여 그 추출된 부분을 포함하는 새로운 배열을 반환.

var myArray = new Array('a', 'b', 'c', 'd', 'e');
myArray = myArray.slice(1, 4); // starts at index 1 and extracts all elements
                               // until index 3, returning [ "b", "c", "d"]

splice(indx,count_to_remove,addElement1,addElement,…)

주어진 인덱스 요소를 포함하여 count_to_remove만큼 삭제하고 주어진 요소로 바꿈.

var myArray = new Array('1', '2', '3', '4', '5');
myArray.splice(1, 3, 'a', 'b', 'c', 'd');
// myArray is now ["1", "a", "b", "c", "d", "5"]
// This code started at index one (or where the "2" was),
// removed 3 elements there, and then inserted all consecutive
// elements in its place.

reverse()

배열의 요소들의 순서를 뒤집음.

var myArray = new Array('1', '2', '3');
myArray.reverse();
// transposes the array so that myArray = ["3", "2", "1"]

sort()

배열 요소들을 정렬

var myArray = new Array('Wind', 'Rain', 'Fire');
myArray.sort();
// sorts the array so that myArray = [ "Fire", "Rain", "Wind" ]

콜백함수를 인자로 주면 배열을 정렬하는 기준을 바꿀 수 있음.

var sortFn = function(a, b){
  if (a[a.length - 1] < b[b.length - 1]) return -1;
  if (a[a.length - 1] > b[b.length - 1]) return 1;
  if (a[a.length - 1] == b[b.length - 1]) return 0;
}
myArray.sort(sortFn);
// sorts the array so that myArray = ["Wind","Fire","Rain"]
  • indexOf(searchElement [, fromIndex)])

배열에서 searchElement를 검색하고 그 인덱스를 반환.

var a = ['a', 'b', 'a', 'b', 'a'];
console.log(a.indexOf('b')); // logs 1
// Now try again, starting from after the last match
console.log(a.indexOf('b', 2)); // logs 3
console.log(a.indexOf('z')); // logs -1, because 'z' was not found

lastIndexOf(searchElement [, fromIndex)])

배열의 뒤쪽부터 요소를 찾음.

var a = ['a', 'b', 'c', 'd', 'a', 'b'];
console.log(a.lastIndexOf('b')); // logs 5
// Now try again, starting from before the last match
console.log(a.lastIndexOf('b', 4)); // logs 1
console.log(a.lastIndexOf('z')); // logs -1
저작자표시 비영리 변경금지 (새창열림)
    'Web/JavaScript' 카테고리의 다른 글
    • Javascript 이벤트 루프
    • 클로저
    • 자바스크립트의 this, 함수 this 바인딩
    • 자바스크립트의 함수
    Camilla
    Camilla
    BI Engineer Data Warehouse & Visualization

    티스토리툴바