如何利用映射函数为歌曲匹配不重复的父流派
问题
需要将歌曲的子流派映射到对应的父流派,具体需求如下:
现有歌曲对象数组:
const songs = [ { track_name: "name of track" , track_genres: ["chamber pop","indie pop"] }, { track_name: "name of track 2" , track_genres: ["dutch r&b","indie soul", "indie pop"] }, { track_name: "name of track 3" , track_genres: ["indie pop","chamber pop","indie soul"] } ];
以及流派映射数组:
const genres = [ { name: "Pop", children: [{name:"chamber pop"},{name:"indie pop"}] }, { name: "R&B", children: [{name:"dutch r&b"}] }, { name: "Soul", children: [{name:"indie soul"}] } ];
要求为每首歌曲遍历其track_genres,利用genres数组分配对应的父流派,且父流派不能重复,预期输出如下:
const songs = [ { track_name: "name of track", track_genres: ["chamber pop", "indie pop"], parent_genres: ["Pop"] }, { track_name: "name of track 2", track_genres: ["dutch r&b", "indie soul", "indie pop"], parent_genres: ["R&B","Soul","Pop"] }, { track_name: "name of track 3", track_genres: ["indie pop", "chamber pop", "indie soul"], parent_genres: ["Pop", "Soul"] } ];
解决方案
思路
先提前构建子流派到父流派的映射表,后续查找父流派时可直接通过键值对快速匹配,避免重复遍历genres数组。之后遍历每首歌曲,根据子流派找到对应父流派,用集合自动去重后转成数组,添加到歌曲对象中。
代码实现
// 构建子流派到父流派的映射表 const subToParentMap = {}; genres.forEach(parentGenre => { parentGenre.children.forEach(child => { subToParentMap[child.name] = parentGenre.name; }); }); // 处理每首歌曲,添加去重后的父流派 const processedSongs = songs.map(song => { const parentSet = new Set(); song.track_genres.forEach(subGenre => { const parent = subToParentMap[subGenre]; if (parent) { parentSet.add(parent); } }); return { ...song, parent_genres: Array.from(parentSet) }; }); console.log(processedSongs);
代码说明
- 映射表构建:遍历
genres数组,将每个子流派名称作为键,对应父流派名称作为值存入subToParentMap,实现O(1)时间复杂度的父流派查找。 - 歌曲处理:
- 使用
map方法遍历原歌曲数组,返回新对象避免修改原数据; - 借助
Set的唯一性自动去除重复的父流派; - 将
Set转为数组后,作为parent_genres属性添加到新的歌曲对象中。
- 使用
内容的提问来源于stack exchange,提问作者NNS
相关产品推荐
相关产品推荐

