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

如何按以' ago'结尾的元素将数组拆分为不均匀块?

拆分数组为以包含" ago"的元素结尾的不均匀块

要把给定数组拆分成多个子数组,每个子数组的最后一个元素必须是包含 ago(空格加ago)的字符串,可以用以下JavaScript代码实现:

const arrExample = [
  "Blah","559","86,758","4.05","2.38","-4.48%","-0.44%","13,562","30d ago", 
  "Trall","531","210,676","16","15","-3.8%","4,955","403d ago", 
  "Shibu","506","991,748","84","6.71%","5,897","667d ago",
  "Mommy","404","35,083","1.64","1.64","-8.38%","17%","7,378","323d ago",
  "Rocket","403","274",".4088",".355","-","-","483","47h ago"
];

const splitByAgo = (arr) => {
  const result = [];
  let currentChunk = [];
  
  for (const item of arr) {
    currentChunk.push(item);
    // 检查当前元素是否包含" ago"
    if (item.includes(' ago')) {
      result.push(currentChunk);
      currentChunk = []; // 重置当前块
    }
  }
  
  // 处理数组末尾可能存在的未完成块(如果有的话)
  if (currentChunk.length > 0) {
    result.push(currentChunk);
  }
  
  return result;
};

// 使用示例
const splitResult = splitByAgo(arrExample);
console.log(splitResult);

代码说明

  • 用result数组保存最终拆分后的所有子数组,currentChunk临时存储正在收集的单个块。
  • 遍历原数组时,逐个把元素加入currentChunk。
  • 一旦遇到包含 ago的元素,就把当前收集好的块存入result,并清空currentChunk开始下一个块的收集。
  • 最后做个兜底检查:如果原数组末尾没有以 ago元素结尾,剩余的元素也会被作为一个块存入结果。

运行这段代码后,得到的splitResult就是按要求拆分后的数组,每个子数组都以xxx ago结尾。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:22:07