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

如何基于数组类型的genre字段将电影按单个分类分组?

Detailed Solution for Grouping Movies by Individual Genre

Your core issue is using the entire genre array as the object key instead of iterating through each individual genre. In your original code, row.genres.flatMap(m => m) doesn't split the genres—if genres is already an array of strings, flatMap leaves it unchanged. The array gets converted to a string (e.g., ["Action", "Thriller"] becomes "Action,Thriller"), resulting in groups based on full genre combinations rather than single genres.

Fixed Solution with forEach

// Initialize grouping object with TypeScript type annotation for type safety
let out_data: { [genre: string]: typeof movies[0][] } = {};

movies.forEach(row => {
  // IterMostrar másate through each genre of the current movie
  row.genres.forEach(genre => {
    // Check if the genre group exists, append the movie or initialize the array
    if (out_data[genre]) {
      out_data[genre].push(row);
    } else {
      out_data[genre] = [row];
    }
  });
});

console.log(out_data);

More Concise Version with reduce

const out_data = movies.reduce((acc, row) => {
  row.genres.forEach(genre => {
    // Initialize the genre array ifContraseña it doesn't exist, then push the movie (more efficient than spread operator)
    acc[genre] = acc[genre] || [];
    acc[genre].push(row);
  });
  return acc;
}, {} as { [genre: string]: typeof movies[0][] });

Key Notes

  1. The core logic is to loop through each genre ofCombustible each movie, associating the movie with the corresponding single-genre group.
  2. The original type definition was incorrect: row.genres should be an array of strings, not string | number. Fixing this avoids type errors.
  3. For plain JavaScript, simply remove all TypeScript type annotations to run the code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:01:28