如何将二维锯齿数组的指定列转换为新数组?
提取二维锯齿数组的指定列并转为新数组
针对你的需求,这里提供几种JavaScript的实现方式:
方法一:使用map()方法(推荐)
map()是最简洁高效的方式,它会遍历原数组的每一行,提取指定索引的元素并组成新数组:
const array = [ [0, 1, 'z', 0], [1, 0, 's', 1], [0, 1, 'x', 0], [1, 0, 'a', 1], ]; // 指定目标列的索引(示例中是第3列,索引从0开始为2) const targetColumnIndex = 2; const expectedOutput = array.map(row => row[targetColumnIndex]); console.log(expectedOutput); // 输出: ['z', 's', 'x', 'a']
如果处理的是不规则锯齿数组(部分行可能没有目标列),可以用可选链操作符避免报错,还能过滤掉undefined值:
const safeOutput = array .map(row => row?.[targetColumnIndex]) .filter(val => val !== undefined);
方法二:使用for循环(适用于需要自定义逻辑的场景)
如果需要更精细的控制(比如添加额外判断),可以用普通的for循环:
const array = [ [0, 1, 'z', 0], [1, 0, 's', 1], [0, 1, 'x', 0], [1, 0, 'a', 1], ]; const targetColumnIndex = 2; const expectedOutput = []; for (let i = 0; i < array.length; i++) { // 检查当前行是否包含目标列,防止索引越界 if (array[i].length > targetColumnIndex) { expectedOutput.push(array[i][targetColumnIndex]); } } console.log(expectedOutput); // 输出: ['z', 's', 'x', 'a']
内容的提问来源于stack exchange,提问作者Arrow
相关产品推荐
相关产品推荐

