【问题标题】:How to sum values of fields for a unique property of an array multiple objects?如何对数组多个对象的唯一属性的字段值求和?
【发布时间】:2020-07-17 07:15:11
【问题描述】:

所以我有这个数据,其中包含一个对象数组,这些对象是博客信息,它们有作者、标题、喜欢、链接等。

我不想做的是在这组数据中获得最多赞的作者。

   const blogs = [ { _id: "5a422a851b54a676234d17f7", title: "React patterns", author: "Michael Chan", url: "https://reactpatterns.com/", __v: 0 }, { _id: "5a422aa71b54a676234d17f8", title: "Go To Statement Considered Harmful", author: "Edsger W. Dijkstra", url: "http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html", likes: null, __v: 0 }, { _id: "5a422b3a1b54a676234d17f9", title: "Canonical string reduction", author: "Edsger W. Dijkstra", url: "http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD808.html", likes: 12, __v: 0 }, { _id: "5a422b891b54a676234d17fa", title: "First class tests", author: "Robert C. Martin", url: "http://blog.cleancoder.com/uncle-bob/2017/05/05/TestDefinitions.htmll", likes: 10, __v: 0 }, { _id: "5a422ba71b54a676234d17fb", title: "TDD harms architecture", author: "Robert C. Martin", url: "http://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html", likes: 0, __v: 0 }, { _id: "5a422bc61b54a676234d17fc", title: "Type wars", author: "Robert C. Martin", url: "http://blog.cleancoder.com/uncle-bob/2016/05/01/TypeWars.html", likes: 2, __v: 0 }

例如:

getAuthorWithMostLikes(blogs)

它会检查数组,将每篇文章中每个作者的点赞数相加 并返回例如:

{author: Robert C. Martin, totalLikes: 12}

我怎样才能以干净的方式实现这一目标?我已经“解决”了它,但我认为代码非常混乱且不可读

这是我的代码:

const likesByAuthor = (blogs) =>{
    const blogsWhereThereIsAnAuthor = blogs.filter(blog=> blog.author)
    console.log("length of filtered array", blogsWhereThereIsAnAuthor.length)
    let authorsAndLikes = []
    let contin = undefined;
    blogsWhereThereIsAnAuthor.forEach((blog, index) => {
        let author = blog.author;
        let likes = blog.likes;
        // initialize concentrado
        console.log("loop for: ", author)
        if (!likes){
            return false
        }
        if (authorsAndLikes.length < 1){
            authorsAndLikes.push({author, likes})
            console.log("initial data", authorsAndLikes)
            return
        }

        authorsAndLikes.forEach((item) => {
            console.log(item.author, "|", blog.author, item.author === blog.author)
            if (item.author === blog.author) {
                console.log("case 1: existing author", item.author, "|", blog.author)
                console.log(item)
                item.likes += blog.likes;
                console.log(item)
                console.log(authorsAndLikes)
                contin = false;
                return false;
            }
            contin = true;

        })
        if (contin !== false) {
            console.log("case 2: new author, adding it to concentrado array", blog.author)
            authorsAndLikes.push({"author": author, "likes": likes})
            console.log(authorsAndLikes)
            console.log("end of iteration case 2")
        }
    })

    return authorsAndLikes;
}

const mostLikes = (blogs) =>{
    const likesCountByAuthor = likesByAuthor(blogs)
    return likesCountByAuthor.reduce((curr, sum) => curr.likes > sum.likes ? curr : sum)
}

如何使用更简洁的代码或更有效的方式实现相同的结果?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    一种更简洁的方法是创建一个像这样的对象:

    {
       author: likes
    }
    

    而不是对象列表。如果你想要这个列表,这个对象可以很容易地变成一个列表。

    我的解决方案利用了reduce()

    const likesByAuthor = (blogs) =>{
        return blogs.reduce((likes, blog) => {
            if (blog.likes)
                if (likes[blog.author])
                    likes[blog.author] += blog.likes;
                else
                    likes[blog.author] = blog.likes;
            return likes;
        }, {});
    }
    

    【讨论】:

    • 你的代码不适合我,我得到这个结果: { _id: "5a422a851b54a676234d17f7" , title: "React patterns" , author: "Michael Chan" , url: "reactpatterns.com" , __v: 0, Edsger W. Dijkstra: NaN, Robert C. Martin: NaN }
    • @AlejandroRosales 感谢您的评论。我错过了一些让它正常工作的细节。查看我的编辑,应该会产生更好的结果。
    • 哇,我不知道你可以这样使用reduce函数,你太棒了,谢谢!
    • @AlejandroRosales 这里的主要思想是reduce() 可以将数组转换为任何其他数据结构。这里我将数组转换为对象,但您也可以将数组转换为另一个数组。在后一种情况下,您应该首先考虑map()
    • @AlejandroRosales 此外,您可以使用手动for 循环甚至forEach() 来执行此操作。您最初的尝试似乎比必要的复杂得多。记住只做你需要的工作,不要做更多。
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2016-11-27
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2013-10-14
    相关资源
    最近更新 更多