1

I have an array of objects like so:

[{state: CA, value: 1}, {state: CA, value: 1}, {state: NY, value: 10}]

I would like the final result to be an object that contains the aggregates of the value for the same states:

{CA: 2, NY: 10}

I have this code below to do that:

let arr = [{state: 'CA', value: 1}, {state: 'CA', value: 1}, {state: 'NY', value: 10}];

let finalObj = {};

arr.map(function(item) {
  let state = item.state;
  if (!finalObj[state]) {
      finalObj[state] = item.value;
  }else {
      finalObj[state] += item.value;
  }
});

console.log(finalObj);

Is there a better way to do this rather than having those if and else checks inside of the map function?

1 Answer 1

1

First I recommend forEach instead of map if you want a simple loop. However in this case reduce is what you really want. I think this is the shortest way to do this I can think of:

const arr = [{state: 'CA', value: 1}, {state: 'CA', value: 1}, {state: 'NY', value: 10}];

const finalObj = arr.reduce((acc, item) => {
  acc[item.state] = (acc[item.state] || 0) + item.value;
  return acc;
}, {});

You can just replace the if/else with always using an assignment and just doing (acc[item.state] || 0) to always get a valid number.

Another option could be to only do the if part (which I think is a pretty clean solution):

const arr = [{state: 'CA', value: 1}, {state: 'CA', value: 1}, {state: 'NY', value: 10}];

const finalObj = arr.reduce((acc, item) => {
  if(!acc[item.state]) {
    acc[item.state] = 0;
  }
  acc[item.state] += item.value;
  return acc;
}, {});

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

Comments

Your Answer

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