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

JavaScript 如何从带周前缀的字符串数组中提取去重周标识生成新数组

实现方案

你可以通过字符串拆分+去重的逻辑完成需求,以下是两种常用实现方式:

方法1:基于Set去重(推荐,代码简洁)

let data = ['week1_aopCrop', 'week1_actCrop', 'week2_aopCrop', 'week2_actCrop'];
// 1. 遍历每个元素按下划线拆分取前缀 2. 用Set自动去重 3. 转回普通数组
const result = [...new Set(data.map(item => item.split('_')[0]))];
console.log(result); // 输出 ['week1', 'week2']

方法2:基于filter+indexOf去重(兼容更低版本ES规范)

let data = ['week1_aopCrop', 'week1_actCrop', 'week2_aopCrop', 'week2_actCrop'];
const prefixArr = data.map(item => item.split('_')[0]);
// 只保留每个前缀第一次出现的元素
const result = prefixArr.filter((item, index, arr) => arr.indexOf(item) === index);
console.log(result); // 输出 ['week1', 'week2']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:15:07