繁体   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