You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Lodash或原生数组函数拆分二维数组为两个一维数组?

解决方法

原生JavaScript实现

直接使用Array.map()方法,遍历原数组的每个子数组,分别提取索引0和索引1的元素即可:

const data = [
    [200, 3],
    [400, 4],
    [2344, 8],
    [34543, 2],
];

const array1 = data.map(item => item[0]);
const array2 = data.map(item => item[1]);

console.log(array1); // [200, 400, 2344, 34543]
console.log(array2); // [3, 4, 8, 2]

map()的作用是对数组的每个元素执行指定函数,并返回新数组,这里我们只需要从每个子数组中取出对应位置的元素即可。

Lodash实现

Lodash提供了更简洁的实现方式,两种思路可选:

方法1:使用_.map()

Lodash的_.map()支持直接传入索引值作为迭代器,快速提取对应位置的元素:

const _ = require('lodash');

const data = [
    [200, 3],
    [400, 4],
    [2344, 8],
    [34543, 2],
];

const array1 = _.map(data, 0);
const array2 = _.map(data, 1);

console.log(array1); // [200, 400, 2344, 34543]
console.log(array2); // [3, 4, 8, 2]

方法2:使用_.unzip()

_.unzip()可以直接将二维数组"解压"为按列分组的数组,再通过解构赋值得到两个目标数组:

const _ = require('lodash');

const data = [
    [200, 3],
    [400, 4],
    [2344, 8],
    [34543, 2],
];

const [array1, array2] = _.unzip(data);

console.log(array1); // [200, 400, 2344, 34543]
console.log(array2); // [3, 4, 8, 2]

内容的提问来源于stack exchange,提问作者TommyD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:21:32