Method using map and filter
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006288', identifier: 'Six two double eight'},
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }]
var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
let newStructureInfos = structureElements.map((ele)=>{
return structureInfos.filter((item)=>item.name === ele)
}).flat();
console.log(newStructureInfos)
Another approach using filter or includes
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006288', identifier: 'Six two double eight'},
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }]
var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
let newinfo = structureInfos.filter((item)=> structureElements.includes(item.name))
console.log(newinfo)
Approach utilizing loop with spread operator
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006288', identifier: 'Six two double eight'},
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }]
var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
let newInfo = [];
for(let item of structureInfos){
if(structureElements.includes(item.name)){
newInfo = [...newInfo,item]
}
}
console.log(newInfo);
Looping method to find matching elements
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006288', identifier: 'Six two double eight'},
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }]
var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
let Info = []
for(let stinfo of structureInfos){
for(let stele of structureElements){
if(stinfo.name === stele){
Info.push(stinfo);
break;
}
}
}
console.log(Info)
Using forEach method to match elements
var structureInfos = [{ name: 'HMDB0006285', identifier: 'Six two eight 5' },
{ name: 'HMDB0006288', identifier: 'Six two double eight'},
{ name: 'HMDB0006293', identifier: 'Six two nine three' },
{ name: 'HMDB0006294', identifier: 'Six two Nine Four' }]
var structureElements = [ 'HMDB0006285', 'HMDB0006293', 'HMDB0006294' ]
let newInfo = [];
structureInfos.forEach((element)=>{
for(let i=0; i<structureElements.length; i++){
if(element.name === structureElements[i]){
newInfo.push(element);
break;
}
}
})
console.log(newInfo)