I am trying to filter an array of object (mainArr ) with dynamically updating object which has list of array (arrTofilter) which looks like bellow , I have 2 test inputs one of them is working as expected but the other one is failing.
let mainArr = [{
AREA: "INDIA",
GROUP_DESC: "Group A",
BUSINESS_ID: "1",
SUB_REGION: "KARNATAKA"
}, {
AREA: "INDIA",
GROUP_DESC: "Group A",
BUSINESS_ID: "2",
SUB_REGION: "Tamilnadu"
}, {
AREA: "INDIA",
GROUP_DESC: "Group C",
BUSINESS_ID: "3",
SUB_REGION: "Kerala"
}, {
AREA: "AFRICA",
GROUP_DESC: "Group D",
BUSINESS_ID: "4",
SUB_REGION: "Nigeria"
}];
//input 1 : input array
let arrTofilter = {
AREA: [],
GROUP_DESC: ['Group A', 'Group D'],
BUSINESS_ID: ['2'],
SUB_REGION: []
};
//so far tried code
const finalArr = mainArr.filter(({
GROUP_DESC,
BUSINESS_ID
}) => arrTofilter.GROUP_DESC.includes(GROUP_DESC) && arrTofilter.BUSINESS_ID.includes(BUSINESS_ID));
The above code works fine if the input array (arrTofilter) is like scenario 1,
in second scenario if the input array is like bellow then code fails , How can i make this work for both the inputs?
//input 2 : input array
let arrTofilter = {AREA: [], GROUP_DESC: ['Group A','Group D'], BUSINESS_ID: [], SUB_REGION: []};
Note: just removing my && statement will work but my input array is huge and even the main array so I can do && for multiple inputs but again if the user sends in single input this wont work
CodePudding user response:
You should be able to check if for example arrTofilter.GROUP_DESC
is empty or not (by checking the length of the array). If it's empty, then it should not be included as a filter. Do this for all four potential filters (AREA, GROUP_DESC, BUSINESS_ID and SUB_REGION).
const finalArr = mainArr.filter(({
AREA
GROUP_DESC,
BUSINESS_ID,
SUB_REGION
}) => (arrTofilter.AREA.length === 0 || arrTofilter.AREA.includes(AREA)) &&
(arrTofilter.GROUP_DESC.length === 0 || arrTofilter.GROUP_DESC.includes(GROUP_DESC)) &&
(arrTofilter.BUSINESS_ID.length === 0 || arrTofilter.BUSINESS_ID.includes(BUSINESS_ID)) &&
(arrTofilter.SUB_REGION.length === 0 || arrTofilter.SUB_REGION.includes(SUB_REGION));