Here is what I tried. Also order is part of a query so this works, I am just not posting the rest of the code so it doesn't get messy. I was getting errors on the paymentsResults[i].filter() saying it is not function . Anyways, if there is a better way to write it, please let me know. Appreciate it.
const getCatType = order => {
if (
order.type === "Invoice" ||
order.type === "One-time" ||
order.type === "Free"
) {
return "Once";
} else if (order.type === "Semester") {
return "Recurring";
}
};
for (let i = 0; i < paymentsResults.length; i++) {
const paymentsOnce = paymentsResults[i].filter(o => getCatType(o) === "Once");
}
Using a switch would be more useful. And then all you need to do it filter out the objects where they match - no need for an additional loop.
function getCatType(order) {
switch(order.type) {
case 'Invoice':
case 'One-time':
case 'Free': return 'Once';
case 'Semester': return 'Recurring';
default: return null;
}
}
const paymentsResults = [
{ type: 'Invoice', id: 1 },
{ type: 'Semester', id: 2 },
{ type: 'Free', id: 3 },
{ type: 'One-time', id: 4 }
];
function typeOfPayment(type) {
return paymentsResults.filter(order => {
return getCatType(order) === type;
});
}
console.log(typeOfPayment('Once'));
console.log(typeOfPayment('Recurring'));
You can use reduce and also you can check for the types you need directly in the reduce cb, mix this with a regex and you can extract what ever types of orders you want by creating a simple array with the types you need. Assuming your paymentsResults are something like this array you can do this:
const paymentsResults = [
{
order: {
type: 'Invoice',
total: 10
},
price: 2
},
{
order: {
type: 'One-time',
total: 11
}
},
{
order: {
type: 'Free',
total: 12
}
},
{
order: {
type: 'Semester',
total: 13
}
},
];
let extract = ['Invoice', 'One-time', 'Free'];
const regex = new RegExp(extract.join('|'), 'i');
let paymentsOnce = paymentsResults.reduce((acc, obj) => {
if (regex.test(obj.order.type)) acc.push(obj);
return acc;
}, []);
console.log(paymentsOnce);
I assume you are confused with what filter() is actually supposed to do.
filter() is an Array-Function iterating over the given Array and returning the objects that fit the filter-conditions defined in the callback function.
Therefore you don't need the for-Loop to get into each Item of your array, but simply call your filter-function on the array itself.
This only applies if you have an Array of Objects with the key type in paymentsResults. Sadly you didn't provide your origin data-structure.
If it is not like I assumed, then please comment down below, what your data structure looks like.
for (let i = 0; i < paymentsResults.length; i++) {
const paymentsOnce = paymentsResults[i].filter(o => getCatType(o) === "Once");
}
Will become:
// ONLY GIVEN IF YOUR STRUCTURE LOOKS LIKE
// paymentsResults = [{type: 'Thing'}, {type: 'Thing'}, ...];
const paymentsOnce = paymentsResults.filter(o => getCatType(o) === "Once");