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

如何修改datasearch函数实现comp单元素时的数组严格匹配?

修改datasearch函数实现匹配逻辑切换

需求明确

  • 单元素comp数组(如['bbb']):仅返回包含严格匹配该元素的子数组
  • 多元素comp数组(如['bbb','fff']):保留原有逻辑——返回包含某个元素能覆盖所有comp项的子数组

修改后的代码

function datasearch() {
    let array = [['a', 'bbb', 'c'], ['r', 'bbbfff', 'y'], ['w', 'bbbfffkkk', 'u']];
    let comp = ['bbb'];
    let ans = [];
    for (let i = 0; i < array.length; i++) {        
        for (el of array[i]) {
            // 根据comp长度切换匹配逻辑
            const matchCondition = comp.length === 1 
                ? el === comp[0] 
                : comp.every(y => el.includes(y));
            if (matchCondition) {
                ans.push(array[i]);
                break;
            }
        }
    }
    console.log(ans);
}

效果验证

  1. 当comp = ['bbb']时,输出结果:[[ 'a', 'bbb', 'c' ]],严格匹配单元素需求
  2. 当comp = ['bbb','fff']时,输出结果:[[ 'r', 'bbbfff', 'y' ], [ 'w', 'bbbfffkkk', 'u' ]],保持原有多元素匹配逻辑不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:33:20