首页 > 解决方案 > 针对另一个对象数组过滤对象数组。删除数组值与另一个对象数组中的值匹配的项

问题描述

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

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

为了澄清,我将比较 inchordLibrary中的每个项目badNotes和 in 中的每个项目,chordLibrary如果它的数组值与badNotes.

在以下示例中,您可以看到 in 中的第一项chordLibrary包含数组 value 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 解决方案还可以。

谢谢!

标签: javascriptarraysobjectfilterforeach

解决方案


In the filter you can use a custom method that searches in the notesInChord if any of them are found in badNotes using find as follows:

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) );


推荐阅读