首页 > 解决方案 > 在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 数组。

标签: javascriptarrays

解决方案


您可以通过将外部数组的索引作为内部数组的索引来减少数组,反之亦然。

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; }


推荐阅读