Reputation: 341
I've used .filter
successfully in the past, but I can't figure out this use case.
I want to return a clone of the array chordLibrary
(presumably using .filter
). But I want to remove any items/objects from this new array where any array value of the property name notesInChord
happens to match any of the array values of badNotes.keyIndex
.
To clarify, I will compare each item in chordLibrary
against every item in badNotes
and remove an item from chordLibrary
if its array values matches any of the array values in any of the items items in badNotes
.
In the following example, you can see that the first item in chordLibrary
includes the array value 5
, and so that item is removed in the result.
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' }
];
I assume I need to nest or use a for loop or forEach to do this, but I can't figure it out.
ES6 solutions are ok.
Thanks!
Upvotes: 0
Views: 41
Reputation: 28424
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) );
Upvotes: 1