You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用映射函数为歌曲匹配不重复的父流派

问题

需要将歌曲的子流派映射到对应的父流派,具体需求如下:
现有歌曲对象数组:

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);

代码说明

  1. 映射表构建:遍历genres数组,将每个子流派名称作为键,对应父流派名称作为值存入subToParentMap,实现O(1)时间复杂度的父流派查找。
  2. 歌曲处理:
    • 使用map方法遍历原歌曲数组,返回新对象避免修改原数据;
    • 借助Set的唯一性自动去除重复的父流派;
    • 将Set转为数组后,作为parent_genres属性添加到新的歌曲对象中。

内容的提问来源于stack exchange,提问作者NNS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 23:42:03