在一系列对象中找到最喜欢博客的人

lau*_*lla 5 javascript arrays loops object

我有一系列博客对象,如何找到喜欢总数最多的作者?

我尝试过使用for循环,将具有不同作者的每个对象推送到一个单独的数组中,然后计算该数组中点赞的总数。我很难将对象相互比较,并且很难为同一作者获得多个数组。

const blogs = [
  {
    title: 'First',
    author: 'Jane',
    likes: 4,
  },
  {
    title: 'Second',
    author: 'Joe',
    likes: 1,
  },
  {
    title: 'Third',
    author: 'Jane',
    likes: 7,
  },
  {
    title: 'Fourth',
    author: 'Jack',
    likes: 1,
  },
  {
    title: 'Fifth',
    author: 'Joe',
    likes: 5,
  }
]
Run Code Online (Sandbox Code Playgroud)

作者的数量不受限制,在此示例中,结果应为:

{
    author: 'Jane',
    likes: 11,
  }
Run Code Online (Sandbox Code Playgroud)

Cod*_*iac 12

您可以使用reduce,将每个作者映射到对象上,然后像添加对象一样

const blogs = [ { title: 'First', author: 'Jane', likes: 4, }, { title: 'Second', author: 'Joe', likes: 1, }, { title: 'Third', author: 'Jane', likes: 7, }, { title: 'Fourth', author: 'Jack', likes: 1, }, { title: 'Fourth', author: 'Joe', likes: 5, } ]

let authorLikes = blogs.reduce((op, {author, likes}) => {
  op[author] = op[author] || 0
  op[author] += likes
  return op
},{})

console.log(authorLikes)
Run Code Online (Sandbox Code Playgroud)

您可以进一步扩展以获得更多喜欢

// to find most likes
let mostLikes = Object.keys(authorLikes).sort((a,b)=> authorLikes[b] - authorLikes[a])[0]

console.log(mostLikes, authorLikes[mostLikes])
Run Code Online (Sandbox Code Playgroud)