绕过过滤器方法中的元素

时间:2019-10-09 20:35:26

标签: javascript

这里是一个代码(由于@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

预先感谢...

1 个答案:

答案 0 :(得分:3)

您可以创建性能最低的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);