javascript - 针对另一个对象数组过滤对象数组。删除数组值与另一个对象数组中的值匹配的项
问题描述
我过去曾.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 解决方案还可以。
谢谢!
解决方案
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) );
推荐阅读
- postgresql - 如何使用 postgresql 从两个单独的时间测量间隔时间
- javascript - 编译为 JavaScript 时,有没有办法在 Haxe 中对类型进行别名?
- javascript - 反应窗口卸载事件不会触发
- python - 熊猫“部分融化”或“集体融化”
- azure - 如何使用 Arm 模板更新现有 Azure Vm 规模集
- vb.net - Keyboard.SendKeys 是 Forms.Sendkeys 的更新?
- angular - Cordova + Angular 4 + GTM(谷歌标签管理器)需要的项目?
- sublimetext3 - 从目录路径安装 Sublime 包
- javascript - Firefox、触摸事件和“平滑”滚动行为——导致不滚动
- r - 差异表达基因分析:如何对不同临床矩阵的表达矩阵进行t.test?