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

在MS Office Script中将嵌套数组转换为一维数组(无法使用array.flat())

在MS Office Script中实现数组扁平化的方案

由于Office Script运行环境不支持Array.flat()方法,我们可以通过以下几种手动实现的方式完成嵌套数组到一维数组的转换:

方法1:手动双层遍历拼接

这是最直观的实现方式,通过两层循环逐个提取子数组中的元素并添加到结果数组:

function main(workbook: ExcelScript.Workbook) {
  const nestedArray = [[1],[2],[3],[4],["a","b","c"],["d","e","f"]];
  const flattenedArray: (number | string)[] = [];
  
  nestedArray.forEach(subArray => {
    subArray.forEach(item => {
      flattenedArray.push(item);
    });
  });
  
  console.log(flattenedArray); // 输出: [1,2,3,4,"a","b","c","d","e","f"]
}

方法2:使用reduce方法合并

利用数组的reduce方法,将每个子数组与累加器数组进行合并,代码更简洁:

function main(workbook: ExcelScript.Workbook) {
  const nestedArray = [[1],[2],[3],[4],["a","b","c"],["d","e","f"]];
  const flattenedArray = nestedArray.reduce((acc, curr) => acc.concat(curr), []);
  
  console.log(flattenedArray); // 输出: [1,2,3,4,"a","b","c","d","e","f"]
}

扩展:支持多层嵌套的通用扁平化函数

如果你的数组存在更深层次的嵌套(比如[[1,[2,3]],[4]]),可以实现一个递归函数来处理:

function main(workbook: ExcelScript.Workbook) {
  const nestedArray = [[1,[2,3]],[4],["a",["b","c"]]];
  
  function flattenArray(arr: any[]): any[] {
    let result: any[] = [];
    arr.forEach(item => {
      if (Array.isArray(item)) {
        result = result.concat(flattenArray(item));
      } else {
        result.push(item);
      }
    });
    return result;
  }
  
  const flattenedArray = flattenArray(nestedArray);
  console.log(flattenedArray); // 输出: [1,2,3,4,"a","b","c"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:57:06