I have an array of objects like below, where I want to calculate the sum of job_security, skill_development and company_culture these fields.
reviews = [
{
id: 1,
job_security: '2.0',
skill_development: '3.0',
company_culture: '4.0',
is_anonymous: false,
pros: 'Test 1...',
cons: "Test 1...",
created_at: '2022-10-19T19:07:18.000Z',
},
{
id: 2,
job_security: '3.0',
skill_development: '1.0',
company_culture: '2.0',
is_anonymous: false,
pros: 'Test 2...',
cons: "Test 2...",
created_at: '2022-10-19T19:07:25.000Z',
},
{
id: 3,
job_security: '4.0',
skill_development: '1.0',
company_culture: '2.0',
is_anonymous: false,
pros: 'Test 3...',
cons: "Test 3...",
created_at: '2022-10-19T19:07:35.000Z',
}
]
I am expecting an output like this, where total sums of all the fields will return as an object
{
job_security: '4.0',
skill_development: '6.0',
company_culture: '7.0',
}
This is what I have done :
const filteredKeys = [
'job_security'
'company_culture',
'skill_development',
];
reviews.forEach((review: any) => {
Object.keys(review).reduce(
(accu: any, key: string) => {
if (filteredKeys.includes(key)) {
const rating = Number(review[key]);
accu[key] = accu[key] || rating;
accu[key] += rating;
}
return accu;
},
Object.create(null)
);
});
2.0 + 3.0 + 4.0 ≠ 4.0,3.0 + 1.0 + 1.0 ≠ 6.0,4.0 + 2.0 + 2.0 ≠ 7.0I hope people will still get the idea that it's supposed to be the sum. I'm just saying the question would be better if it used the correct sums. People who are into programming are often quite particular about numerical details and consistency. Many of us have made a career of it.