In my project I make a request to the api database and get all my posts I then filter them by their stage value and create a new array for each stage. But I also want to loop through each stage array (opportunityPosts, prospectPosts, proposalPosts) and get the total cost value. I know this can be done with reduce() but if I try call reduce on any of these arrays I get an error because the array is not yet defined.
So how can I get the total cost of each stage?
Here's some demo code that I made:
let posts = [
{
"stage": "Opportunity",
"cost": 1200
},
{
"stage": "Prospect",
"cost": 1500
},
{
"stage": "Opportunity",
"cost": 10000
},
{
"stage": "Proposal",
"cost": 1900
},
{
"stage": "Prospect",
"cost": 500
}
];
let opportunityPosts = posts.filter(post => {
if( post.stage == 'Opportunity' ){
return post;
}
});
let prospectPosts = posts.filter(post => {
if( post.stage == 'Prospect' ){
return post;
}
});
let proposalPosts = posts.filter(post => {
if( post.stage == 'Proposal' ){
return post;
}
});
console.log(opportunityPosts);
console.log(prospectPosts);
console.log(proposalPosts);