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

如何合并二维数组中子数组内的字符串并去除空格?

问题:处理二维数组去除子数组字符串空格并合并

输入示例

[
  [ 'time' ],
  [ 'user full name' ],
  [ 'affected user' ],
  [ 'event context' ],
  [ 'component' ],
  [ 'event name' ],
  [ 'description' ],
  [ 'origin' ],
  [ 'ip address' ]
]

期望输出

[
  [ 'time' ],
  [ 'userfullname' ],
  [ 'affecteduser' ],
  [ 'eventcontext' ],
  [ 'component' ],
  [ 'eventname' ],
  [ 'description' ],
  [ 'origin' ],
  [ 'ipaddress' ]
]

原代码问题分析

你写的函数存在两个关键问题:

  • headerRow[i]是子数组(比如['user full name']),并非字符串,直接调用toLowerCase()会抛出错误
  • split()未传参时会按空格拆分字符串,但你没有将拆分后的数组合并回无空格的字符串,反而把拆分后的数组直接推入结果,完全不符合需求

修正后的解决方案

用map遍历原数组,对每个子数组执行以下操作:

  1. 取出子数组中的唯一字符串元素
  2. 转换为小写
  3. 移除所有空格(可通过正则替换或拆分后合并实现)
  4. 将处理后的字符串重新包装为子数组返回

代码实现:

const processHeaderArray = (headerRow) => {
  return headerRow.map(item => {
    // 取出子数组字符串、转小写、移除所有空格
    const processedStr = item[0].toLowerCase().replace(/\s+/g, '');
    // 重新包装为子数组返回
    return [processedStr];
  });
};

// 测试示例
const originalArray = [
  [ 'time' ],
  [ 'user full name' ],
  [ 'affected user' ],
  [ 'event context' ],
  [ 'component' ],
  [ 'event name' ],
  [ 'description' ],
  [ 'origin' ],
  [ 'ip address' ]
];

const resultArray = processHeaderArray(originalArray);
console.log(resultArray);

补充说明

如果不想使用正则,也可以用split(' ').join('')替代replace(/\s+/g, ''),效果一致:

const processedStr = item[0].toLowerCase().split(' ').join('');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:38:28