繁体   English   中英

想知道如何使用另一个列表过滤列表

[英]Wondering how to filter a list using another list

我对代码还很陌生,遇到了一个我真的不知道如何面对的问题。 在我的 code.org 作业中,我需要按艺术家过滤歌曲。 有代码从一组艺术家中随机选择 1 位艺术家。 现在通过在列表中使用那个过滤后的艺术家,我必须从该艺术家的同一数据集中获取歌曲,

 function artistPicker() { var index; filteredArtist = []; filteredSongName = []; index = randomNumber(0, artistData.length - 1); var artistName = artistData[index]; appendItem(filteredArtist, artistName); for (var i = 0; i < artistData.length; i++) { if (songNameData[i] == filteredArtist) { appendItem(filteredSongName, songNameData[i]); } } setScreen("displayScreen"); setText("textOutput", artistName + filteredSongName); }

这是我到目前为止。 它会随机选择一位艺术家,但不会过滤掉所选艺术家的歌曲。

如果我理解正确的话,你有这样的数据

const data = [
 {artist: 'my band', song: 'my song'}, 
 {artist: 'my band', song: 'my other song'},
 {artist: 'your band', song: 'your song'}
]

然后你可以 select 随机艺术家并按该艺术家过滤列表:

const randomIx = Math.floor(Math.random() * data.length)
const artist = data[randomIx].artist
const allArtistEntries = data.filter(entry => entry.artist === artist)
const artistSongTitles = allArtistEntries.map(entry => entry.song)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM