这是一个代码(由于@omgitsgod),它基于slides array查找refer array中性能最低的匹配短语。



var slides = [
{ id: 1, performance: 20, guided_phrases: ["I was sent", "I don't know", "to earth"] },
{ id: 2, performance: 30, guided_phrases: ["to earth"] },
{ id: 3, performance: 40, guided_phrases: ["to protect you"] },
{ id: 4, performance: 10, guided_phrases: ["I was sent"] },
{ id: 5, performance: 5, guided_phrases: ["I was sent"] }

];

let refer = ["I was sent", "to earth", "to protect you"]; // we want to check which slide id contain each refer array strings

let bypass_slide = 4; // I want to bypass this silde id
slides.splice(bypass_slide - 1, 1); // so I just remove the bypass_slide from slides array

let id = [];

/* we just go through each string in refer array and make calculations to find the slides with the lowest performance which includes each of refer array elements*/
  for(let i = 0; i < refer.length; i++){

  id.push(slides.filter(x => x.performance === Math.min(...slides.filter(slide => slide.guided_phrases.includes(refer[i])).map(x => x.performance)))[0].id)

    console.log(id)
}





这段代码可以正常工作,但是我认为这里需要进行大的修改:

如您所见,我想忽略并绕过幻灯片ID 4,因此我只是删除了bypass_slide的幻灯片ID,并对新的slides array进行了计算,我确信这不是最好的方法。

我想知道是否存在通过在此过滤器方法中进行一些修改来绕过幻灯片ID 4的解决方案:

slides.filter(x => x.performance === Math.min(...slides.filter(slide => slide.guided_phrases.includes(refer[i])).map(x => x.performance)))[0].id


提前致谢...

最佳答案

您可以创建具有最低性能和短语的Map作为键,然后映射id作为结果。



var slides = [{ id: 1, performance: 20, guided_phrases: ["I was sent", "I don't know", "to earth"] }, { id: 2, performance: 30, guided_phrases: ["to earth"] }, { id: 3, performance: 40, guided_phrases: ["to protect you"] }, { id: 4, performance: 10, guided_phrases: ["I was sent"] }, { id: 5, performance: 5, guided_phrases: ["I was sent"] }],
    bypass = [4],
    map = slides.reduce((m, o) => {
        if (bypass.includes(o.id)) return m;
        o.guided_phrases.forEach(p => {
            if (!m.has(p) || m.get(p).performance > o.performance) m.set(p, o);
        });
        return m;
    }, new Map),
    refer = ["I was sent", "to earth", "to protect you", "or not"],
    result = refer.map(k => map.has(k) ? map.get(k).id : 0);

console.log(result);

10-06 07:37