1

I'm trying to find the sum of each type in my array of roomList... Tried out reduce() but it is only returning the last value. Is there a way to achieve this using reduce()... I'm open to other approaches also.

let roomList=[
        {value:1,type:2},{value:2,type:2},{value:3,type:2},{value:4,type:3}, 
        {value:5,type:4},{value:6,type:4},{value:7,type:6},{value:8,type:6}, 
        {value:9,type:1},{value:10,type:8},{value:11,type:8},{value:12,type:8}
];
roomList.reduce((acc,obj)=>{
   acc[obj.type]=obj.value;
   return acc;
},{})

I'm expecting a result like this {1:9,2:6,3:4,4:11...}

2 Answers 2

2

You only get the last value because you overwrite and not add. Change your reduce code to this:

roomList.reduce((acc,obj)=>{
    acc[obj.type] = (acc[obj.type] || 0) + obj.value;
    return acc;
},{})

To clarify this line:

acc[obj.type] = (acc[obj.type] || 0) + obj.value;

We cannot simply do this:

acc[obj.type] += obj.value;

Because acc[obj.type] might not be initialized and therefore return an undefined value. Instead we do acc[obj.type] || 0 to retrieve the value and if it is falsy use a value of 0.

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

Comments

1

You could use map to accumulate the values

let roomList=[ {value:1,type:2},{value:2,type:2},{value:3,type:2},{value:4,type:3}, {value:5,type:4},{value:6,type:4},{value:7,type:6},{value:8,type:6}, {value:9,type:1},{value:10,type:8},{value:11,type:8},{value:12,type:8} ];
g={}
roomList.map(o=>{
  !g[o.type]? g[o.type]=o.value : g[o.type]= g[o.type]+o.value
})
console.log(g)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.