Array.from()

딱이·2021년 6월 24일
0

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

대상 객체를 복사해 새로운 Array를 반환해 준다.

String to Array

Array.from('abc');
// ["a", "b", "c"]

Set to Array

const set = new Set([1, 2, 3]);

Array.from(set);
// [1, 2, 3]

Map to Array

const map = new Map([1, 2], [2, 4]);

Array.from(map);
// [[1, 2], [2, 4]]

const mapper = new Map([["1", "a"], ["2", "b"], ["3", "c"]]);
Array.from(mapper.values());
// ["a", "b", "c"]

Array.from(mapper.ㅏkeys());
// ["1", "2", "3"]

📌 사용

Array.from([1, 2, 3], x => x + x);
// Array [2, 4, 6]

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

// 응용.ver 범위값 내 배수 집합 
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

range(1, 10, 2);
// [1, 3, 5, 7, 9]
profile
뚝딱뚝딱 FE

0개의 댓글