我过去曾经成功使用过.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解决方案还可以。
谢谢!
答案 0 :(得分: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) );