gpt4 book ai didi

javascript - 在Javascript中获取数组的每个第n个值并将每个第n个值插入数组

转载 作者:行者123 更新时间:2023-11-28 17:29:52 25 4
gpt4 key购买 nike

我有一个数组,里面的数组如下所示:

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 个值。

编辑:解决方案是 transposing a 2D array ,正如 CRice 所提到的。

最佳答案

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

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

关于javascript - 在Javascript中获取数组的每个第n个值并将每个第n个值插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50705993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com