I have an array of objects that i need to filter by a certain criteria. I'm having trouble figuring out the logic for the if statement within the for loop. I've attached a code snippet where you can adjust the criteria and see the problem I'm trying to solve. Any thoughts or advice are greatly appreciated, thanks!
With the following criteria I should only end up with 1 found item in my foundItems array:
const criteria = {
title: 'title',
character: 'Z',
type: ['second'],
};
This should(and does) return all three items:
const criteria = {
title: 'title',
character: '',
type: [],
};
This should return the first two items:
const criteria = {
title: 'title',
character: 'R',
type: [],
};
This should return all three items:
const criteria = {
title: '',
character: '',
type: ['first','second'],
};
const data = [
{
label: {
title: 'A title',
},
character: 'R',
type: 'first',
},
{
label: {
title: 'Another title',
},
character: 'R',
type: 'second',
},
{
label: {
title: 'A more interesting title',
},
character: 'Z',
type: 'second',
},
];
const criteria = {
title: 'title',
character: 'Z',
type: ['second'],
};
const createRegEx = (value) => {
const regex = value
.split(' ')
.filter(Boolean)
.map((word) => `(?=^.*${word})`)
.join('');
return new RegExp(regex, 'i');
}
const foundItems = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
if (
item.label.title.match(createRegEx(criteria.title))
|| item.character === criteria.character
|| criteria.type.includes(item.type)
) {
foundItems[foundItems.length] = item;
}
}
console.log(foundItems);
&&rather than||?titleexists in all three data elements. So the given criteria and the logical OR will end up with all three selected. What am I missing?typecriteria while the data element for type is astringtype?