gpt4 book ai didi

javascript - 使用 lodash 连接多个二维数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:48 25 4
gpt4 key购买 nike

我有多个二维数组,我想将它们连接成一个二维数组:

var data = [
[["x"], ["value1"], ["value2"], ["valu3"]],
[["data1"], [0], [1], [2]],
[["data2"], [2], [1], [0]]
];

想要的结果:

var result = [
["x", "data1", "data2"],
["value1", 0, 2],
["value2", 1, 1],
["value3", 2, 0]
];

到目前为止,我尝试使用 apply 压缩和连接,但我得不到我想要的结果:

var data = [
[["x"], ["value1"], ["value2"], ["valu3"]],
[["data1"], [0], [1], [2]],
[["data2"], [2], [1], [0]]
];

var result = _.zipWith.apply(_, _.concat(data))

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>

最佳答案

使用常规 ES6 javascript 怎么样? :)

const data = [
[
['x'],
['value1'],
['value2'],
['valu3'],
],
[
['data1'],
[0],
[1],
[2],
],
[
['data2'],
[2],
[1],
[0],
],
];

const ret = data.map(x => x.reduce((tmp, y) => [
...tmp,
...y,
], []));

console.log(ret);


在 ES5 中按照要求

var data = [
[
['x'],
['value1'],
['value2'],
['valu3'],
],
[
['data1'],
[0],
[1],
[2],
],
[
['data2'],
[2],
[1],
[0],
],
];

var result = [];

for (let i = 0; i < data.length; i += 1) {
var oneArray = [];

for (let j = 0; j < data[i].length; j += 1) {
for (let k = 0; k < data[i][j].length; k += 1) {
oneArray.push(data[i][j][k]);
}
}

result.push(oneArray);
}

console.log(result);

关于javascript - 使用 lodash 连接多个二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540109/

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