Hi I’m creating an array
this.data = [{
label: 'Total',
count: details.request.length,
}, {
label: 'In-Progress',
count: details.request.filter((obj) =>
obj.statusId === 0 ||
obj.statusId === 1 ||
obj.statusId === 3 ||
obj.statusId === 4
? obj
: null,
).length,
}, {
label: 'Success',
count: details.request.filter(({ statusId }) =>
statusId === 6 ? statusId : null,
).length,
additionalObj: details.request.filter((obj) =>
obj.statusId === 6 ? obj : null,
),
}, {
label: 'Failed',
count: details.request.filter(({ statusId }) =>
statusId === 2 || statusId === 5 ? statusId : null,
).length,
additionalObj: details.request.filter((obj) =>
obj.statusId === 2 || obj.statusId === 5 ? obj : null,
),
}];
I’m creating the array in the structured I need, but have optimize this, I’m using array filter
multiple times while calculating count
and also for additionalObj
. I’m not sure how can I use filter once for both calculating count and additionalObj. Would be great if someone can help me on optimizing my code.
FYI, this is the details structure:
details = {
request: []
}
2
Answers
Is there any specific reason you are using filter instead of a for loop?
The code can be written as the following, which uses only a single loop:
Your question is not good, neither your code. But I’m just going to say why you’re code is bad and how to fix it.
The most critical thing in your code regarding PERFORMANCE is you’re iterating
details.request
multiple times, while you could do the filtering once.Iterating an array or list multiple times for different filters in this way can be avoided by using
reduce
for your case.Here is how you can do it by iterating
details.request
only once withreduce
and create an object that has properties representing the status so you don’t need to store that too:and here is how to do it your way in case you need it data to be in that specific shape for an Api: