是否有更好的方法可以使用Lodash库来重构此功能?
我的目标是列出博客列表,并找到最多的博客返回这样的对象的作者{作者:string,博客:numbers}。我很成功,但我想知道使用lodash的解决方案的更好方法。谢谢你!
let blogs = [
{ title: 'sorceror stone', author: 'rowling', likes: 5 },
{ title: 'prisoner of azkaban', author: 'rowling', likes: 13 },
{ title: 'green mile', author: 'king', likes: 3 },
{ title: 'oliver twist', author: 'dickens', likes: 7 },
{ title: 'the half blood prince', author: 'rowling', likes: 16 },
{ title: 'david copperfield', author: 'dickens', likes: 10 },
{ title: 'christmas carol', author: 'dickens', likes: 3 },
{ title: 'tale of two cities', author: 'dickens', likes: 20 },
]
const mostBlogs = (blogs) => {
let authorsByBlogs = _.countBy(blogs, 'author')
let maxBlogs = _.max(_.values(authorsByBlogs))
let author = _.findKey(authorsByBlogs, (o) => {
return o === maxBlogs
})
return { author: author, blogs: maxBlogs }
}
console.log(mostBlogs(blogs)) // { author: "dickens", blogs: 4}
My goal was to take a list of blogs and find the author with the most blogs returning an object like this { author: String, blogs: Number }. I was successful, but I want to know a better approach to my solution using Lodash. Thank You!
let blogs = [
{ title: 'sorceror stone', author: 'rowling', likes: 5 },
{ title: 'prisoner of azkaban', author: 'rowling', likes: 13 },
{ title: 'green mile', author: 'king', likes: 3 },
{ title: 'oliver twist', author: 'dickens', likes: 7 },
{ title: 'the half blood prince', author: 'rowling', likes: 16 },
{ title: 'david copperfield', author: 'dickens', likes: 10 },
{ title: 'christmas carol', author: 'dickens', likes: 3 },
{ title: 'tale of two cities', author: 'dickens', likes: 20 },
]
const mostBlogs = (blogs) => {
let authorsByBlogs = _.countBy(blogs, 'author')
let maxBlogs = _.max(_.values(authorsByBlogs))
let author = _.findKey(authorsByBlogs, (o) => {
return o === maxBlogs
})
return { author: author, blogs: maxBlogs }
}
console.log(mostBlogs(blogs)) // { author: "dickens", blogs: 4}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是使用Lodash的
_。Flow()
(请参阅代码中的注释)的重构功能的重构。并且使用 lodash/fp :
This is a refactor of your function using lodash's
_.flow()
(see comments in code):And the same idea using lodash/fp: