개요
- Python 의
zip함수처럼 두 개의 배열을 아래와 같이 압축(zip)하려는 상황
map(), Array.from(), Array.prototype.fill() 를 사용하여 다음과 같이 만들 수 있다.
- 두 개의 Arr 의 길이가 같지 않으면
undefined 가 생긴다.
const arr1 = ['a', 'b', 'c'];
const arr2 = ['1', '2', '3'];
-> const newArr = [['a', '1'], ['b', '2'], ['c', '3']];
map()
let a = [9, 8, 7];
let b = ["1", "2", "3"];
let zip = a.map(function (e, i) {
return [e, b[i]];
});
console.log(zip);
Array.from()
let a = [9, 8, 7, 6];
let b = ["90", "80", "70", "60"];
let zip = (a, b) =>
Array.from(Array(Math.max(a.length, b.length)), (_, i) => [a[i], b[i]]);
console.log(zip(a, b));
Array.prototype.fill()
let a = [7, 8, 9];
let b = ["70", "80", "90"];
let zip = (a, b) =>
Array(Math.max(a.length, b.length))
.fill()
.map((_, i) => [a[i], b[i]]);
console.log(zip(a, b));