簡體   English   中英

如何使用.includes對數組進行.filter過濾?

[英]How to .filter an array against an array with .includes?

我看過許多其他帖子,但無法解決我的案件。

我正在開發一個音樂/和弦演奏程序,我想過濾掉所有包含一個或多個音符(程序中的數字)超出關鍵范圍的和弦(又名對象)。

我有一個名為chordLibrary的數組, chordLibrary充滿了對象(例如{notesInChord: [5, 8], chordName: 'Major'} )。 我還有另一個帶有數字的數組( outOfKeyNotes = [11, 12]; )。 我想過濾並僅返回chordLibrary中不包含元素notesInChordoutOfKeyNotes中的數字的notesInChord

例如:

 // THIS is the original array: const chordLibrary = [ { notesInChord: [5, 8], chordName: 'Major' }, { notesInChord: [5, 8, 11], chordName: 'Dominant 7th' }, { notesInChord: [4, 8, 12], chordName: 'Minor Major 7th' } ]; // THIS is what I hope to end up with after filtering for the array [11,12]: let chordsInKey = [ { notesInChord: [5, 8], chordName: 'Major' }, ]; 

這是我當前無法正常運行的程序。 它只是返回整個原始數組。

 const chordLibrary = [ { notesInChord: [5, 8], chordName: 'Major' }, { notesInChord: [5, 8, 11], chordName: 'Dominant 7th' }, { notesInChord: [4, 8, 12], chordName: 'Minor Major 7th' } ]; let outOfKeyNotes = [11, 12]; console.log(chordLibrary.length); let chordsInKey = chordLibrary.filter(function(item) { return !outOfKeyNotes.includes(item.notesInChord); }); console.log(chordsInKey); console.log(chordsInKey.length); 

如果我更改程序,使chordLibrary只是數字值的數組而不是對象的數組,那么它可以正常工作。 只是不符合我的需要。 這是一個可行的示例:

 let chordLibrary = [1,2,3,11,12]; let outOfKeyNotes = [11, 12]; console.log(chordLibrary.length); let chordsInKey = chordLibrary.filter(function(item) { return !outOfKeyNotes.includes(item); }); console.log(chordsInKey); console.log(chordsInKey.length); 

我想念什么? 謝謝

您可以使用Array#some()檢查notesInChordoutOfKeyNotes存在任何notesInChord

 const chordLibrary = [ { notesInChord: [5, 8], chordName: 'Major' }, { notesInChord: [5, 8, 11], chordName: 'Dominant 7th' }, { notesInChord: [4, 8, 12], chordName: 'Minor Major 7th' } ]; let outOfKeyNotes = [11, 12]; let chordsInKey = chordLibrary.filter(function(item) { return !item.notesInChord.some(function(v){ return outOfKeyNotes.includes(v); }); }); console.log(chordsInKey); 

您嘗試使用includes來查看值數組是否包含另一個值數組。

相反,您可以在過濾機制中使用Array.every ,以確保數組中的每個元素都通過特定的測試。

我會改變

return !outOfKeyNotes.includes(item.notesInChord);

return item.notesInChord.every(note => !outOfKeyNotes.includes(note));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM