-1

Can I make this function cleaner by using not forEach() but .reduce() please?

const post = [
  {
    id: "1",
    dateOfPost: "15.10.2020",
    postTitle: "...",
    postText: "...",
    },
    comments: [
      {
        id: "1",
        dateOfComment: "15.10.2020",
        gravatar: "...",
        nicName: "...",
        commentText: "...",
        starRating: 3,
        likeCount: 8,
        dislikeCount: 1
      },
      {
        id: "2",
        dateOfComment: "15.10.2020",
        gravatar: "...",
        nicName: "...",
        commentText: "...",
        starRating: 5,
        likeCount: 1,
        dislikeCount: 1
      },
    ]
  }
];

const postComments = post[0].comments;
const starRatingAverage = () => {
  let starRatingAVG = 0;
  postComments.forEach(comment => {
    starRatingAVG = starRatingAVG + comment.starRating
  })
  return starRatingAVG = starRatingAVG / postComments.length;
}

I'm just a beginner and I'm training to do things right. So I will be grateful for all your help. Thanks.

Cid
  • 14,968
  • 4
  • 30
  • 45

2 Answers2

0

You can get the sum of starRating using Array.reduce and map the average to the each element of posts using Array.map.

const post = [{
  id: "1",
  dateOfPost: "15.10.2020",
  postTitle: "...",
  postText: "...",
  comments: [{
      id: "1",
      dateOfComment: "15.10.2020",
      gravatar: "...",
      nicName: "...",
      commentText: "...",
      starRating: 3,
      likeCount: 8,
      dislikeCount: 1
    },
    {
      id: "2",
      dateOfComment: "15.10.2020",
      gravatar: "...",
      nicName: "...",
      commentText: "...",
      starRating: 5,
      likeCount: 1,
      dislikeCount: 1
    },
  ]
}];

const output = post.map(({ comments }) => (comments.length > 0 ? comments.reduce((acc, cur) => acc + cur.starRating, 0) / comments.length : 0));
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

Yes. Replace this:

  let starRatingAVG = 0;
  postComments.forEach(comment => {
    starRatingAVG = starRatingAVG + comment.starRating
  })

With this:

  let starRatingAVG = postComments.reduce((acc, x) => acc + x.starRating, 0);