如何使用includes()按test关键字对字符串数组进行分组?
用includes()实现按test关键字分组数组
嘿,这事儿不难,咱们直接用JavaScript的数组遍历方法结合includes()就能搞定你的分组需求,我给你两种实用的实现方式:
固定关键字的基础实现
如果你的分组关键字只有test1和test2,直接初始化目标结构然后遍历判断就行:
var records = ["test1 name1", "test2 name2", "test1 name3", "test1 name4"]; // 先创建好两个空数组的结果容器 var obj = [[], []]; // 遍历每个元素进行分组 records.forEach(item => { // 用includes()检查当前字符串是否包含test1 if (item.includes("test1")) { obj[0].push(item); } // 再检查是否包含test2 else if (item.includes("test2")) { obj[1].push(item); } }); console.log(obj); // 输出结果正好是你要的:[["test1 name1", "test1 name3", "test1 name4"], ["test2 name2"]]
支持扩展关键字的灵活实现
如果以后可能要加更多类似test3、test4的分组关键字,咱们可以把关键字做成数组,动态生成分组,这样不用改太多代码:
var records = ["test1 name1", "test2 name2", "test1 name3", "test1 name4"]; // 把所有要分组的关键字放在这里,以后加新的直接加数组元素就行 var groupKeywords = ["test1", "test2"]; // 根据关键字数量生成对应数量的空数组 var obj = groupKeywords.map(() => []); records.forEach(item => { // 找到当前元素匹配的第一个关键字的索引 const matchIndex = groupKeywords.findIndex(key => item.includes(key)); // 如果找到匹配的关键字,就把元素推入对应分组 if (matchIndex !== -1) { obj[matchIndex].push(item); } }); console.log(obj); // 同样能得到你需要的分组结果
两种方式核心都是用includes()来判断字符串里是否包含目标关键字,然后把元素分配到对应的分组里~
内容的提问来源于stack exchange,提问作者Stfvns
相关产品推荐
相关产品推荐

