javascript - 在Javascript中获取每个数组的第n个值并将每个第n个值推入数组
问题描述
我有一个数组,里面的数组看起来像这样:
var arr = [
["title1", "title2", "title3"],
["description1", "description2", "description3"],
["id1", "id2", "id3"]
];
而且,我想从数组中取出每个第 n 个值并将其推送到一个新对象中,因此它看起来像这样:
var newArr = [
["title1", "description1", "id1"],
["title2", "description2", "id2"],
["title3", "description3", "id3"],
];
我知道在这种情况下我可以使用 for 循环,但不确定如何获取每个第 n 个值。
编辑:正如 CRice 所提到的, 解决方案是转置一个 2D 数组。
解决方案
您可以通过将外部数组的索引作为内部数组的索引来减少数组,反之亦然。
var array = [["title1", "title2", "title3"], ["description1", "description2", "description3"], ["id1", "id2", "id3"]],
result = array.reduce(
(r, a, i) => {
a.forEach((v, j) => (r[j] = r[j] || [])[i] = v);
return r;
},
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- android - recyclerview 滚动时折叠/隐藏特定布局
- azure - 逻辑应用的 IP 白名单
- mysql - 如何在 mysql 中取消引用/处理 json 数组?
- python - 如何在 Python 中同时打印输出
- php - Yii2删除ActiveRecord错误信息有时是数组,有时不是?
- sql - 根据行号选择 ID
- javascript - jQuery Bootstrap Tooltip - 鼠标悬停时显示的 2 个工具提示
- reporting-services - 当前季度日期参数 SSRS 的最后一天
- javascript - 使用 Google 增强型电子商务,在添加/从购物车中删除时,数量值应该代表什么?
- kubernetes - pod.containers.spec.resources 不起作用(限制和请求)Kubernetes