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

JavaScript如何根据元素内容按指定结尾规则拆分数组为多个分块

JS数组按指定收尾元素拆分实现

需求描述

给定字符串数组,需将其拆分为多个子数组分块,规则如下:

  • 每个分块的最后一个元素,必须是以goose结尾的字符串
  • 每个分块内,收尾元素之前的元素数量无固定规律
  • 输入元素自带两个强约束,不需要额外做异常兼容:
    • goose永远只会出现在元素的末尾位置
    • 非分块收尾的元素永远不会包含goose字段,不存在goose foo这类内容,仅存在duck goose这类合法收尾元素

输入示例:

const words = [
 'duck foo bar',
 'duck',
 'duck bing ',
 'bing',
 'Bloop#12 goose',
 'duck 12',
 'duck goose',
  // ...更多元素
]

期望输出:

const result = [
 [
   'duck foo bar',
   'duck',
   'duck bing',
   'bing',
   'Bloop#12 goose',
 ], 
 [
   'duck 12',
   'duck goose',
 ], 
 // ...更多分块
];

实现代码

直接单次遍历即可完成,时间复杂度O(n),没有额外性能开销:

function chunkArrayByGoose(originArr) {
  const chunkResult = [];
  let tempChunk = [];
  for (const str of originArr) {
    // 先去除首尾多余空格,兼容示例里'duck bing '这类带末尾空格的脏数据
    const formatStr = str.trim();
    tempChunk.push(formatStr);
    // 命中收尾元素,封存当前分块
    if (formatStr.endsWith('goose')) {
      chunkResult.push(tempChunk);
      tempChunk = [];
    }
  }
  // 如果数组末尾存在没有goose收尾的残余元素,默认丢弃;如果需要保留可以把tempChunk非空时push进结果
  return chunkResult;
}

// 测试调用
const testWords = [
 'duck foo bar',
 'duck',
 'duck bing ',
 'bing',
 'Bloop#12 goose',
 'duck 12',
 'duck goose'
];
console.log(chunkArrayByGoose(testWords));

逻辑说明

  • 遍历全程维护一个临时数组存储当前正在收集的分块元素
  • 每遍历到一个元素,先做去首尾空格的格式化处理,再塞入临时分块
  • 检测到当前元素以goose结尾时,说明当前分块收集完成,推入最终结果后重置临时分块,开始收集下一段
  • 因为题目已经给出强约束,不需要额外做字符串包含判断,直接用endsWith做结尾匹配即可,逻辑最简单性能最高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.08 16:15:17