简体   繁体   中英

How to get Total Length or Count on Two Different Arrays

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:

在此处输入图片说明

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM