JavaScript 如何创建一个元素数组,对由zip生成的数组中的元素进行解组
我们可以通过使用JavaScript中的不同方法(如Math.max()、Array.prototype.map()、Array.prototype.reduce()和Array.prototype.forEach())对由zip生成的数组中的元素进行解组来创建一个元素数组。这个操作也可以被称为 解包 。
在了解 解包 之前,让我们先了解一下 zip 是什么。
zip 会根据原始数组中的元素位置创建一个分组的元素数组。为了实现这一点,我们可以使用JavaScript的Math.max()、Array.from()和Array.prototype.map()等方法。
方法:
- Math.max() :获取所有参数数组中最长的数组。
- 然后,使用返回值作为长度,利用Array.from()和映射函数创建一个分组元素数组。
- Array.prototype.map() :将每个数组元素转换为一个新的数组。
- 此外,扩展运算符(…)用于表示可作为参数传递给zip函数的变量数量的数组。
示例: 以下示例演示了上述解释的方法。
Javascript
<script>
const zip = (...arrays) => {
const maxLength = Math.max(
...arrays.map(arr => arr.length));
return Array.from({ length: maxLength })
.map((_, i) => {
return Array.from(
{length: arrays.length },
(_, j) => arrays[j][i]);
});
};
console.log(
zip(
[1, "GFG", 0.1],
[2, "GeeksForGeeks", 0.2],
[3, "Geeks", 0.3],
[4, "For", 0.4],
[5, "Geeks", 0.5]
)
);
</script>
输出:
现在让我们看看如何实现 unzip :
- Math.max() :获取数组中最长的子数组。
- Array.prototype.map() :将每个数组元素转换为数组。
- Array.prototype.reduce() 和 Array.prototype.forEach() :
将分组的值映射到单独的数组。 - 最后, Array.prototype.map() 和展开操作符(…)用于将 f 参数应用于每个单独的元素组。
示例: 此示例演示了上述解释的方法。
Javascript
<script>
const unzip = (arr, f) => arr.reduce(
(a, myValue) => (myValue.forEach(
(val, i) => a[i].push(val)), a),
Array.from({
length: Math.max(
...arr.map(myArr => myArr.length)),
}).map(myArr => [])
)
.map(v => f(...v));
console.log(
unzip(
[
[1, 3, 5],
[2, 6, 10],
[3, 9, 15],
],
(...arguments) => arguments
.reduce((acc, j) => acc + j, 0)
)
);
</script>
输出:
[3,6,18]
极客教程