Before anyone calls duplicate please read it through first...
I was trying to use the filter function with multiple conditions but doesn't seem to work and alot of solutions to this roughly come out to say I can do...
const data = [
{CatalogID: -1, SectionID: 0},
{CatalogID: 2, SectionID: 9},
{CatalogID: 2, SectionID: 9},
{CatalogID: -1, SectionID: 0},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6},
{CatalogID: 3, SectionID: 6},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6}
]
data.filter(f=>f.SectionID == 6 && f.SectionID == 0 && f.CatalogID == -1)
let a = data.filter(function(e) {
return e.SectionID == 6 && e.SectionID == 0 && e.CatalogID == -1
});
console.log(a);
But those return empty... But when I loop through the data object, like this...
let holder = [];
for(let i = 0; i < data.length; i++){
if(data[i].SectionID === 6 || data[i].SectionID === 0 || data[i].CatalogID === -1) holder.push(data[i]);
}
console.log(holder);
holder = [];
Then it does the job, but its not pretty.
Is there something glaringly obvious that is wrong with the code I provided, that is not popping out at me?
** EDIT ** The result I am looking for is this...
{CatalogID: -1, SectionID: 0},
{CatalogID: -1, SectionID: 0},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6},
{CatalogID: 3, SectionID: 6},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6}
f.sectionID = 6 && f.sectionID == 0 can't ever be true -- there can only be one sectionID value in a specific object f.
You need to use || to match different values of the same sectionID property. Then use && to combine condition with catalogID.
const data = [
{CatalogID: -1, SectionID: 0},
{CatalogID: 2, SectionID: 9},
{CatalogID: 2, SectionID: 9},
{CatalogID: -1, SectionID: 0},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6},
{CatalogID: 3, SectionID: 6},
{CatalogID: -1, SectionID: 0},
{CatalogID: 3, SectionID: 6}
]
let a = data.filter(f => f.SectionID == 6 || ( f.SectionID == 0 && f.CatalogID == -1))
console.log(a);