【发布时间】:2020-04-15 05:16:18
【问题描述】:
我最初在几个月前的一次采访中遇到了这个问题,现在已经开始解决了。
所以我们有了这个对象数组,目标是找到一个对象,其中的演员在电影中没有出现过一次以上。所以基本上找一部有独特演员的电影。
[
{
name: 'The Dark Knight',
rating: 'PG-13',
year: 2012,
bestScene: {
name: 'fight',
location: 'sewer',
sceneLength: 10,
actors: ['Christian Bale', 'Tom Hardy']
}
},
{
name: 'Good Burger',
rating: 'PG',
year: 1994,
bestScene: {
name: 'jump',
location: 'giant milkshake',
sceneLength: 5,
actors: ['Kenan Thompson', 'Kel Mitchell']
}
},
{
name: 'Sharknado 2: The Second One',
rating: 'TV-14',
year: 2013
},
{
name: 'The Big Short',
rating: 'R',
year: 2015,
bestScene: {
name: 'explanation',
location: 'casino',
sceneLength: 20,
actors: ['Christian Bale', 'Steve Carrell']
}
}
]
我为自己设定的目标是使用函数式方法来解决它,因此我们自然需要像这样清除不存在 bestScene 的对象:
const moviesWithActorsPresent = movies.filter((movie) => movie.bestScene)
然后我可以使用reduce 构造一个对象数组,如下所示:
[
{ 'The Dark Knight': [ 'Christian Bale', 'Tom Hardy' ] },
{ 'Good Burger': [ 'Kenan Thompson', 'Kel Mitchell' ] },
{ 'The Big Short': [ 'Christian Bale', 'Steve Carrell' ] }
]
然后循环使用for 或forEach 并在一个临时变量中跟踪演员,但对我来说这并不是一个优雅的解决方案。
我们可以在这里使用什么 CS 概念来有效地解决它?
【问题讨论】:
标签: javascript arrays functional-programming computer-science