Array.from() 메서드는 유사 배열 객체(array-like object)나 반복 가능한 객체(iterable object)를 얕게 복사해 새로운Array 객체를 만듭니다.
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike
배열로 변환하고자 하는유사 배열 객체나 반복 가능한 객체.
mapFn (Optional)
배열의 모든 요소에 대해 호출할 맵핑 함수.
thisArg (Optional)
mapFn 실행 시에 this로 사용할 값.
새로운 Array 인스턴스.
배열을 만들고 0으로 채우기
let array = Array(n).fill(0);
2차원배열을 만들고 0으로 채우기
let array = Array.from(Array(n), () => Array(n).fill(0))
string을 배열로 바꾸기
Array.from('foo');
// ["f", "o", "o"]
Set에서 배열 만들기
const s = new Set(['foo', window]);
Array.from(s);
// ["foo", window]
Map에서 배열 만들기
const m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
배열 형태를 가진 객체(arguments)에서 배열 만들기
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [1, 2, 3]
Array.from과 화살표 함수 사용하기
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], x => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
n 만큼의 길이를 가지고, index ~ index + 1 까지의 수로 값을 채운 array 생성
let queue = Array.from({ length: n }, (v, i) => i + 1);
// 예 : n:5 [1, 2, 3, 4, 5]
reduce()메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
숫자 배열의 값을 전부 더합니다. 초기값: 0
orders.map(order => {
const {id, quantity} = order;
const prototype = prototypes.find(p => p.id === id);
return prototype.price * quantity;
}).reduce((l, r) => l + r, 0);
sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
arr.sort([compareFunction])
compareFunction Optional
정렬 순서를 정의하는 함수. 생략하면 배열은 각 요소의 문자열 변환에 따라 각 문자의 유니 코드 코드 포인트 값에 따라 정렬됩니다.
참고 : 만약 [2, 5, 3, 1, 4, 10]을 nums.sort()로만 하면 [1, 10, 2, 3, 4, 5]로 정렬됩니다.
sort함수는 기본값으로 정렬하면 배열 원소를 문자열로 변환한 다음 정렬를 합니다.
정렬한 배열. 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.
내림차순 정렬
nums.sort((a, b)=>b-a);
한 자리수 숫자를 오름차순 정렬
nums.sort();
두 자릿수 이상의 숫자를 오름차순 정렬
nums.sort((a, b)=>a-b);