How to get Total Length or Count on Two Different Arrays

Viewed 91

I know the question is hard to understand so I will explain how I want it to be I have this array of data:

const products = [
  {
    name: "Product A",
    reviews: [
      {
        comment: "Good Product",
        username: "Alif",
      },
    ],
  },
  {
    name: "Product B",
    reviews: [
      {
        comment: "Bad Product",
        username: "Alif",
      },
      {
        comment: "Good Product",
        username: "Atif",
      },
      {
        comment: "Ok Product",
        username: "Esha",
      },
    ],
  },
];


products.map(({ reviews }) => {
  console.log(reviews.length);
});

I would like to get the length of the reviews but since both objects are separate which is the Product A and the Product B, I get separated length or count like this:

enter image description here

I would please like the result to be total length of 4 or count of 4, so I thought of merging the array. Are there any other methods to be done?

3 Answers

A naive solution could be:

const products = [{
    name: "Product A",
    reviews: [{
      comment: "Good Product",
      username: "Alif",
    }, ],
  },
  {
    name: "Product B",
    reviews: [{
        comment: "Bad Product",
        username: "Alif",
      },
      {
        comment: "Good Product",
        username: "Atif",
      },
      {
        comment: "Ok Product",
        username: "Esha",
      },
    ],
  },
];

const allProducts = products.flatMap(({
  reviews
}) => reviews);

console.log(allProducts.length);

This maps over each product and extracts the reviews arrays, which are then flattened into a single array.

I would go for a reduce function:

const totalAmountOfReviews = products.reduce((commentCount, product) => {
  return commentCount + product.reviews.length;
}, 0);

console.log(totalAmountOfReviews); // 4

You can use reduce to get the total of reviews

products.reduce((acc, { reviews }) => acc + reviews.length, 0);

const products = [
  {
    name: "Product A",
    reviews: [
      {
        comment: "Good Product",
        username: "Alif",
      },
    ],
  },
  {
    name: "Product B",
    reviews: [
      {
        comment: "Bad Product",
        username: "Alif",
      },
      {
        comment: "Good Product",
        username: "Atif",
      },
      {
        comment: "Ok Product",
        username: "Esha",
      },
    ],
  },
];

const result = products.reduce((acc, { reviews }) => acc + reviews.length, 0);
console.log(result);

Related