JavaScript 배열 관련 함수 총정리

yoo chang heon·2022년 3월 28일
0

JavaScript

목록 보기
3/9

at()

정수 값을 받아 배열에서 해당 값에 해당하는 인덱스 요소 반환(음수의 경우 뒤에서 부터 세줌)

array.at(index);

concat()

인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환 (기존 배열 변경x , 추가된 새로운 배열을 반환)

const array3 = array1.concat(array2); //array1+array2결과가 array3에

copyWithin()

배열의 일부를 얕게 복사한 뒤, 동일한 배열의 다른 위치에 덮어쓰고 그 배열을 반환( 배열의 길이는 변경 x )

arr.copyWithin(target, start, end);
  • 원본 배열 변경
  • start ~ end(end는 포함x) 까지 복사해서 target 위치에 넣음
  • 음수인 경우 인덱스를 배열 끝에서 부터 계산(arr.length+end로 계산)
  • 잘못된 범위일 경우 동작 x

entries()

배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Interator 객체를 반환

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]
  • for of 루프로 반복 가능

every()

배열 안의 모든 요소가 주어진 판별함수를 통과하는지 테스트(Boolean 값 반환)

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

fill()

배열의 시작 인덱스부터 끝 인덱스의 이전까지 정적인 값 하나로 채움

filter()

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

const result = words.filter(word => word.length > 6);

find()

주어진 판별함수를 만족하는 첫번째 요소의 을 반환(없으면 undefined)

const found = array1.find(element => element > 10);

findIndex()

주어진 판별함수를 만족하는 배열의 첫번째 요소에 대한 인덱스 반환(없으면 -1)

console.log(array1.findIndex(isLargeNumber));

flat()

모든 하위배열 요소를 지정한 깊이까지 재구적으로 이어붙인 새로운 배열을 생성
매개변수: 평탄화하고 싶은 깊이

  • 중첩 배열 평탄화
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 빈 값 없애기
const arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]
Copy to Clipboard
대안

flatMap()

먼저 매핑함수를 사용해 각 엘리먼트에 대해 map 수행 후, 결과를 새로운 배열로 평탄화

  • 이는 깊이 1의 flat 이 뒤따르는 map 과 동일하지만, flatMap 은 아주 유용하며 둘을 하나의 메소드로 병합할 때 조금 더 효율적.(flat()+map())
let arr1 = ["it's Sunny in", "", "California"];

arr1.map(x=>x.split(" "));
// [["it's","Sunny","in"],[""],["California"]]

arr1.flatMap(x => x.split(" "));
// ["it's","Sunny","in","California"]
// 다음은 음수는 제거하고 홀수는 1과 짝수로 분리하는 예시입니다.
let a = [5, 4, -3, 20, 17, -33, -4, 18]
//       |\  \  x   |  | \   x   x   |
//      [4,1, 4,   20, 16, 1,       18]

a.flatMap( (n) =>
  (n < 0) ?      [] :
  (n % 2 == 0) ? [n] :
                 [n-1, 1]
)

// expected output: [4, 1, 4, 20, 16, 1, 18]

forEach()

주어진 함수를 배열 요소 각각에 대해 실행

array1.forEach(element => console.log(element));

Array.from()

유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듬

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

groupBy()

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

  • firefox-Nightly에서만 지원.
  • 별도 자바스크립트 라이브러리를 추가해야만 사용가능

includes()

배열이 특정 요소를 포함하고 있는지 판별(Boolean 값 반환)

array1.includes(2)

indexOf()

배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환( 존재하지 않으면 -1을 반환)

Array.isArray()

인자가 Array인지 판별(Boolean 값 리턴)

join()

배열의 모든 요소를 연결해 하나의 문자열로 만듬

keys()

배열의 각 인덱스를 키 깞으로 가지는 새로운 Array Iterator 객체를 반환

lastIndexOf()

배열에서 주어진 값을 발견할 수 있는 마지막 인덱스를 반환(존재하지 않을 시 -1 리턴)

map()

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

Array.of()

인자의 수나 유형에 관계없이 가변 인자를 갖는 새 Array 인스턴스를 만듬

Array.of(7);       // [7]
Array.of(1, 2, 3); // [1, 2, 3]

pop()

배열의 마지막 요소 제거, 그 요소 반환

push()

배열의 끝에 하나 이상의 요소를 추가, 배열의 새로운 길이를 반환

reduce()

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

리듀서 함수 인자

  • 누산기 (acc)
  • 현재 값 (cur)
  • 현재 인덱스 (idx)
  • 원본 배열 (src)
    리듀서 함수의 반환 값은 누산기에 할당되어 반복
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

reduceRight()

누적기에 대해 함수를 적용하고 배열의 가 값은 값을 단일 값으로 줄임

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]

reverse()

배열의 순서를 반전

shift()

첫번째 요소를 제거, 제거된 요소를 반환(길이도 변화 시킴)

slice()

배열의 begin 부터 end(미포함)까지에 대한 얕은 복사본을 새로운 배열 객체로 반환

  • 원본 배열 변화 x
  • 매개변수 하나 사용 시 그 index부터 끝까지
  • 음수 사용시 뒤에서부터 적용
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 1));
// 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"]

some()

배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트( 빈배열은 무조건 false)

sort()

배열의 요소를 정렬한 후 그 배열 반환

  • 원본 배열 변경 o

splice()

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

  • 원본 배열 변경 o
    splice(start, deleteCount, item1, item2)
  • start: 배열의 변경을 시작할 인덱스(음수일 경우 뒤에서 부터)
  • deleteCount: 배열에서 제거할 요소의 수(생략, arr.length- start 보다 크면 모두 제거, 0이하이면 제거 x)
  • item1,item2...: 배열에 추가할 요소( 지정하지 않을 시 요소 제거만 수행)
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"]

toLocaleString()

배열의 요소를 나타내는 문자열을 반환(숫자의 사용 언어에 따른 표현을 포함한 문자열을 반환)

let num = 1234.56789;
console.log(num.toLocaleString("ar-EG"));//١٬٢٣٤٫٥٦٨
console.log(num.toLocaleString("zh-Hans-CN-u-nu-hanidec"));// 一,二三四.五六八
console.log(num.toLocaleString("ko-KR", { style: 'currency', currency: 'KRW' })); //₩1,235

toString()

지정된 배열 및 그 요소를 나타내는 문자열을 반환

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

unshift()

새로운 요소를 배열의 맨 앞에 추가, 새로운 길이 반환

values()

배열의 각 인덱스에 대한 값을 가지는 새로운 Array Iterator 객체를 반환


https://developer.mozilla.org/ko/docs/Web/JavaScript

0개의 댓글