# JavaScript 中壓縮陣列

## 在 JavaScript 中使用 `map` 方法壓縮陣列

JavaScript 中的 `map()` 函式壓縮了兩個一定長度的陣列。但是，如果兩個陣列的長度不匹配，則會導致 `undefined`

``````let a = [9, 8, 7];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
return [e, b[i]];
});
console.log(zip);
``````

`map()` 方法接受的回撥函式將呼叫 `a` 陣列的元素以及與 `a` 集合對映的 `b` 陣列的元素。學習如何以這種方式拉上拉鍊也很簡單。

``````[[9, "1"], [8, "2"], [7, "3"]]
``````

``````let a = [9, 8, 7, 6];
let b = ['1', '2', '3'];
let zip = a.map(function(e, i) {
return [e, b[i]];
});
console.log(zip);
``````

``````[[9, "1"], [8, "2"], [7, "3"], [6, undefined]]
``````

## 在 JavaScript 中使用 `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.from` 方法的例項中將存在兩個陣列；它們將被髮送到箭頭函式。匹配長度後，該過程將對映來自兩個單獨陣列的專案。

``````[[9, "90"], [8, "80"], [7, "70"], [6, "60"]]
``````

``````let a = [9, 8, 7];
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));
``````

``````[[9, "90"], [8, "80"], [7, "70"], [undefined, "60"]]
``````

`Array.prototype.fill()` 方法的工作原理與 `Array.from()` 方法相同。

``````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));
``````

``````[[7, "70"], [8, "80"], [9, "90"]]
``````

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.