【问题标题】:Filter array of objects against another array of objects. Remove items with array values that matches those inside another array of objects针对另一个对象数组过滤对象数组。删除数组值与另一个对象数组中的值匹配的项
【发布时间】:2020-07-02 19:04:30
【问题描述】:

我过去成功使用过.filter,但我无法弄清楚这个用例。

我想返回数组chordLibrary 的克隆(大概使用.filter)。但我想从这个新数组中删除任何项目/对象,其中属性名称 notesInChord 的任何数组值恰好匹配 badNotes.keyIndex 的任何数组值。

为了澄清,我会将chordLibrary 中的每个项目与badNotes 中的每个项目进行比较,并从chordLibrary 中删除一个项目,如果它的数组值匹配badNotes 中任何项目中的任何数组值.

在以下示例中,您可以看到chordLibrary 中的第一项包含数组值5,因此该项目在结果中被删除。

const chordLibrary = [
    { notesInChord: [5, 8], chordName: 'Major' },
    { notesInChord: [4, 8], chordName: 'Minor' },
    { notesInChord: [8], chordName: '5' }
];
const badNotes = [
    {"keyIndex":[1],"keyName":"C#"},
    {"keyIndex":[3],"keyName":"D#"},
    {"keyIndex":[5],"keyName":"E"}
];

// example result: "
const newChordLibrary = [
    { notesInChord: [4, 8], chordName: 'Minor' },
    { notesInChord: [8], chordName: '5' }
];

我假设我需要嵌套或使用 for 循环或 forEach 来执行此操作,但我无法弄清楚。

ES6 解决方案还可以。

谢谢!

【问题讨论】:

    标签: javascript arrays object filter foreach


    【解决方案1】:

    filter 中,您可以使用自定义方法在notesInChord 中搜索(如果在使用find 的badNotes 中找到它们中的任何一个,如下所示:

    const chordLibrary = [
        { notesInChord: [5, 8], chordName: 'Major' },
        { notesInChord: [4, 8], chordName: 'Minor' },
        { notesInChord: [8], chordName: '5' }
    ];
    const badNotes = [
        {"keyIndex":[1],"keyName":"C#"},
        {"keyIndex":[3],"keyName":"D#"},
        {"keyIndex":[5],"keyName":"E"}
    ];
    
    function getGoodNotes(chordList){
         return chordList.filter((chord)=>{
              if(!containsBadNote(chord.notesInChord))
                   return chord;
         });
    }
    function containsBadNote(notesInChord){
         for(let i = 0; i < notesInChord.length; i++){
              var note = notesInChord[i];
              if(badNotes.find((n)=> n.keyIndex[0]==note)!=null)
                   return true;
         }
         return false;
    }
    
    console.log( getGoodNotes(chordLibrary) );

    【讨论】:

    • 太棒了!这似乎有效!我会仔细观察,然后接受。
    猜你喜欢
    • 2018-10-03
    • 2021-05-14
    • 2022-01-23
    • 2019-05-05
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多