본문 바로가기
Frontend/Javascript Typescript

[Javascript] Array.from() 활용하여 배열 생성하기

by 디스코비스킷 2025. 3. 19.
반응형

Array.from()을 활용한 배열 생성 방법

Array.from()은 배열과 유사한 객체(Array-like object)나 이터러블 객체(Iterable object)를 배열로 변환하거나, 특정 로직을 적용해 배열을 생성하는 유용한 메서드이다.

1. 배열과 유사한 객체를 배열로 변환

arguments, NodeList, Set, Map 같은 유사 배열 객체 변환

function example() {
  console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3 }

  const arr = Array.from(arguments); // 유사 배열 → 배열 변환
  console.log(arr); // [1, 2, 3]
}

example(1, 2, 3);

유사 배열 객체(arguments)를 배열로 변환하여 배열 메서드 사용 가능
map(), filter() 등의 배열 메서드를 사용할 수 있게 됨

2. Set을 배열로 변환 (중복 제거)

const set = new Set([1, 2, 3, 3, 4, 5, 5]);
const arr = Array.from(set);
console.log(arr); // [1, 2, 3, 4, 5]

Set을 배열로 변환하여 중복을 제거할 때 유용
[...set]과 동일한 기능 수행

3. Map의 키/값을 배열로 변환

const map = new Map([
  ["name", "Alice"],
  ["age", 25],
  ["job", "Developer"]
]);

const keys = Array.from(map.keys());
console.log(keys); // ["name", "age", "job"]

const values = Array.from(map.values());
console.log(values); // ["Alice", 25, "Developer"]

Map의 키(keys()), 값(values())을 배열로 변환하여 활용 가능

4. 특정 길이의 배열을 생성하면서 초기값 적용

Array.from({ length: n }, () => value)

const arr = Array.from({ length: 5 }, () => 0);
console.log(arr); // [0, 0, 0, 0, 0]

길이가 5이고 모든 요소가 0인 배열 생성

5. 1부터 n까지의 숫자로 배열 생성

const arr = Array.from({ length: 10 }, (_, i) => i + 1);
console.log(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(_, i) => i + 1을 활용하여 1~10 배열 생성

6. 랜덤 숫자로 배열 생성

const randomArr = Array.from({ length: 5 }, () => Math.floor(Math.random() * 100));
console.log(randomArr); // 예: [23, 87, 45, 67, 12]

각 요소가 0~99 사이의 랜덤 숫자로 채워진 배열 생성

7. 문자열을 배열로 변환

const str = "Hello";
const arr = Array.from(str);
console.log(arr); // ["H", "e", "l", "l", "o"]

문자열을 문자 배열로 변환 가능(split('')과 유사)

Array.from() 사용 요약

사용법 설명
Array.from(arguments) 유사 배열을 배열로 변환
Array.from(set) Set을 배열로 변환 (중복 제거)
Array.from(map.keys()) Map의 키를 배열로 변환
Array.from({ length: n }, () => value) n개의 요소를 가진 배열 생성 (초기값 적용)
Array.from({ length: n }, (_, i) => i + 1) 1~n 숫자 배열 생성
Array.from({ length: n }, () => Math.random()) 랜덤 숫자 배열 생성
Array.from("Hello") 문자열을 문자 배열로 변환

배열 변환과 배열 생성 모두 가능하므로 활용도가 높음!

반응형

최근댓글

최근글

© Copyright 2024 ttutta