2

I want to calculate sum of array data in JavaScript.

Array :

[
  {
    red_team: {
      count: 2,
      money: 3000,
    },
    blue_team: {
      count: 10,
      money: 100000,
    },
  },
  {
    red_team: {
      count: 1,
      money: 1000,
    },
    blue_team: {
      count: 100,
      money: 200000,
    },
  }
]

Expected Result :

{
  red_team: {
    count: 3,
    money: 4000,
  },
  blue_team: {
    count: 110,
    money: 300000,
  },
}

Note : red_team & blue_team is an Enum.

how can I calculate it ?

3
  • 1
    Please share your attempt(s) so far Commented Feb 28, 2022 at 18:06
  • 1
    There are many ways to do this. But first you should attempt to figure it out yourself. That is the best way to learn. Start out by looping through the array and keep a value for red_team and a value for blue_team Commented Feb 28, 2022 at 18:08
  • Do you know the amount of objects there are in the array (e.g. since this is a game, do you know the amount of rounds beforehand)? Commented Mar 1, 2022 at 7:31

2 Answers 2

3

Spread the array into lodash's _.mergeWith(), and create a customizer that sums number, but returns undefined for all other types, so that lodash would handle all other cases:

const data = [{"red_team":{"count":2,"money":3000},"blue_team":{"count":10,"money":100000}},{"red_team":{"count":1,"money":1000},"blue_team":{"count":100,"money":200000}}]


const result = _.mergeWith({}, ...data, (a, b) => 
  _.isNumber(a) ? a + b : undefined
)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

Comments

0

Per a comment above, an infinite ways of doing this. I just came up with one (rather verbose admittedly)

Verbose solution:

const arr = [
  {
    red_team: {
      count: 2,
      money: 3000,
    },
    blue_team: {
      count: 10,
      money: 100000,
    },
  },
  {
    red_team: {
      count: 1,
      money: 1000,
    },
    blue_team: {
      count: 100,
      money: 200000,
    },
  }
];

function sumByKeyAndProperty(arr, key, property){
  let sum = 0
  arr.forEach((obj) => {
    sum+=obj[key][property]
  })
  return sum
}

returnObj = {
  red_team: {
    count: sumByKeyAndProperty(arr, 'red_team', 'count'),
    money: sumByKeyAndProperty(arr, 'red_team', 'money'),
  },
  blue_team: {
    count: sumByKeyAndProperty(arr, 'blue_team', 'count'),
    money: sumByKeyAndProperty(arr, 'blue_team', 'money'),
  }
}

console.log(returnObj)

Comments

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.