0

I have a problem and I can't find an answer for that issue, I want to add/sum all values from points in points_sum.

I tried to do this by adding a for loop in the object, but then I get:

'Unexpected token'

How can I do this in the another way?

let sum = 0;
let teams = [
  team1 = {
    name: "Real",
    goal_plus: [3, 4, 2, 1],
    goal_minus: [1, 0, 2, 1],
    points: [3, 3, 3, 1],
    points_sum: for (let i = 0; i < points.length; i++) {
      sum += points[i];
    }
  },
  team2 = {
    name: "Barca",
    goal_plus: [5, 2, 5, 1],
    goal_minus: [1, 0, 0, 1],
    points: [3, 3, 3, 1],
    points_sum: 0
  }
]
0

1 Answer 1

1

You can't add a for loop directly inside an object as a value and also you cannot refer to the object keys or values before it has been created, so even if you could add the for, that part:
i < points.length would thrown an error, something like "points is undefined", since the object is not created yet and points also doesn't exists in memory.

Another thing, arrays keys can't be named, so keys team1 and team2 will be removed from array, only their value will remain (the objects), if you want to keep those names, make the variable teams an object, not an array.

A solution to your problem can be: create a function that receives an array and makes the sum for you, I'm using inside this function, the .reduce() method.

let teams = [
  {
    name: "Real",
    goal_plus: [3, 4, 2, 1],
    goal_minus: [1, 0, 2, 1],
    points: [3, 3, 3, 1],
    points_sum: SumPoints([3, 3, 3, 1]),
  },
  {
    name: "Barca",
    goal_plus: [5, 2, 5, 1],
    goal_minus: [1, 0, 0, 1],
    points: [3, 3, 3, 1],
    points_sum: SumPoints([3, 3, 3, 1])
  }
]

function SumPoints(arr) {
  return arr.reduce((a, b) => a + b, 0)
}

console.log(teams)

Another possible way to solve this, if you can't or don't want to pass the whole array as parameter to a external function, is letting points_sum empty and then after creating the array teams, do some job to calculate, using a loop method such as forEach, see in the below snippet:

let teams = [{
    name: "Real",
    goal_plus: [3, 4, 2, 1],
    goal_minus: [1, 0, 2, 1],
    points: [3, 3, 3, 1],
    points_sum: 0
  },
  {
    name: "Barca",
    goal_plus: [5, 2, 5, 1],
    goal_minus: [1, 0, 0, 1],
    points: [3, 3, 3, 1],
    points_sum: 0
  }
]

teams.forEach(x => {
  x.points_sum = x.points.reduce((a, b) => a + b, 0)
})

console.log(teams)

Sign up to request clarification or add additional context in comments.

1 Comment

OK, I got it. Thank you for help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.