-2

How can I calculate the average of numbers in an array that is in an array?

See the image how I get the data in;

enter image description here

const reviews = [
0: ["5", "1"]
1: ["4"]
2:  ["1", "4", "1"]
3: ["1", "4"]
4:  ["5", "4"]
5: []
etc etc
]

I would like to know the average of each array so:

0: 3
1: 4
2: 2 
etc etc

I work in React. I get the data from a selector in React-Redux. I use this for calculating the average review for each user.

code:

  const reviews = users
    ? users.map((review) => {
        return review
          ? review.reviews.map((reviewen) => {
              return <p>{reviewen.review}</p>;
            })
          : "loading ";
      })
    : "Loading";

  console.log(reviews);

Ali Lotfi
  • 125
  • 1
  • 1
  • 12

1 Answers1

3

I think you are looking for something like this:

const reviews = [
["5", "1"],
["4"],
["1", "4", "1"],
["1", "4"],
["5", "4"]
];
const avgReviews = reviews.map(x => (x.reduce((a,b) => parseInt(a) + parseInt(b), 0) / x.length));
console.log(avgReviews);

Or you could create a new array that combines the average with the aray from which it was calculated.

const reviews = [
["5", "1"],
["4"],
["1", "4", "1"],
["1", "4"],
["5", "4"]
];
const reviews_and_average = reviews.map(x => [x,(x.reduce((a,b) => parseInt(a) + parseInt(b), 0) / x.length)]);
console.log(reviews_and_average);