繁体   English   中英

使用 map 优化嵌套循环,减少,过滤 JavaScript

[英]Optimize nested loops with map, reduce, filter for JavaScript

使用.map() 、 .reduce( .reduce().filter()函数,我如何编写一个有效的例程来派生所有具有流行流派集中存在的.genre标签集中存在.tag广播电台?

// Radio stations
const stations = [
    {
        title: 'BBC Radio 1',
        genre:['Popular', 'Rnb', 'Hip Hop', 'Dance'],
        tag: ['bbc', 'radio 1', 'uk']
    },
    {
        title: 'Classic FM',
        genre:['Classical', 'Orchestra'],
        tag: ['bbc', 'uk']
    },
]
// Popular genres
const popular = [
    'Popular',
    'House',
    'Chillout',
    'Top 40',
    'Drum And Bass'
]
// Tags
const tags = [
    'bbc',
    'uk'
]

我相信这是一种常见的模式,似乎没有很好的记录。 我自己的尝试涉及编写嵌套循环,我认为这可能更干净。 我的数据集包含约 22,000 个条目(我可以根据性能对其进行调整),并在按键时进行搜索。 这将离线运行,我无法使用数据库,甚至是本地数据库。 我想使用; .map() , .reduce( .reduce() , .filter()函数,尽管我知道这些可能会强加 function 调用开销并且我可以使用二叉树。

您确实可以使用filter ,但随后someincludes

let filtered = stations.filter(station =>
    station.genre.some(genre => popular.includes(genre)) &&
    station.tag.some(tag => tags.includes(tag))
);

您可以简单地使用.filter ,并检查两件事:

  1. tag键吗?
  2. 如果有tag键,它是否有任何值?

像这样:

const stationsWithTags = stations.filter(e => e.tag && e.tag.length > 0);

然后使用嵌套在另一个for循环中for循环,以检查genre中的每个项目与popular中的每个项目。 找到匹配项时, return添加到过滤后的变量,退出循环,并评估下一个站。

尝试运行下面的完整代码:

// Radio stations
const stations = [
  {
      title: 'BBC Radio 1',
      genre:['Popular', 'Rnb', 'Hip Hop', 'Dance'],
      tag: ['bbc', 'radio 1', 'uk']
  },
  {
      title: 'Classic FM',
      genre:['Classical', 'Orchestra'],
      tag: ['bbc', 'uk']
  }
]
// Popular genres
const popular = [
  'Popular',
  'House',
  'Chillout',
  'Top 40',
  'Drum And Bass'
]
// Tags
const tags = [
  'bbc',
  'uk'
]

const stationsWithTags = stations.filter(e => e.tag && e.tag.length > 0);

const popularStationsWithTags = stationsWithTags.filter(e => {
  if (e.genre){
    //Check each item in 'genre' against each item in 'popular'
    for (let i = 0; i < e.genre.length; i++){
      for (let j = 0 ; j < popular.length; j++){
        if (e.genre[i] === popular[j]){ //If genre is in 'popular', this item passes filter
          return true;
        } 
      }
    }
  }
})

console.log(popularStationsWithTags);

暂无
暂无

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

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