Reputation: 1518
Here, I am having an array
const arr = [
{
"_id": "5de74ca17a40a48cca18b243",
"index": 0,
"guid": "66275f0b-f1ce-444e-b5e1-85c59ba399ab",
"language": "est",
"tags": ["fugiat", "eu", "ex"]
},
{
"_id": "5de74ca121f6de98b3c1e2c0",
"index": 1,
"guid": "3a89d677-2f73-41ad-99f3-3dcaccce6b37",
"language": "tempor",
"tags": ["sit", "esse", "anim", "non"]
}
]
And I am having a search bar, I have search by tags value inside of the array. If I type fugiat
it should give an o/p with the obj which lies on it.
eg:
[
{
"_id": "5de74ca17a40a48cca18b243",
"index": 0,
"guid": "66275f0b-f1ce-444e-b5e1-85c59ba399ab",
"language": "est",
"tags": ["fugiat", "eu", "ex"]
}
]
I tried and implemented the search with the language it works fine but I tried to do it with tags. It is not working.
my approach for language filter
arr.filter((data) => {
const regex = new RegExp(`${'est'}`, 'gi');
return data.language.match(regex);
})
I'd appreciate some help on this.
Upvotes: 1
Views: 46
Reputation: 6359
You can use includes
method to search in array
.
const arr = [
{
"_id": "5de74ca17a40a48cca18b243",
"index": 0,
"guid": "66275f0b-f1ce-444e-b5e1-85c59ba399ab",
"language": "est",
"tags": ["fugiat", "eu", "ex"]
},
{
"_id": "5de74ca121f6de98b3c1e2c0",
"index": 1,
"guid": "3a89d677-2f73-41ad-99f3-3dcaccce6b37",
"language": "tempor",
"tags": ["sit", "esse", "anim", "non"]
}
];
function filter(key) {
return arr.filter((obj) => obj.tags.includes(key));
}
console.log(filter("fugiat"));
Using Regex
.
const arr = [
{
"_id": "5de74ca17a40a48cca18b243",
"index": 0,
"guid": "66275f0b-f1ce-444e-b5e1-85c59ba399ab",
"language": "est",
"tags": ["fugiat", "eu", "ex"]
},
{
"_id": "5de74ca121f6de98b3c1e2c0",
"index": 1,
"guid": "3a89d677-2f73-41ad-99f3-3dcaccce6b37",
"language": "tempor",
"tags": ["sit", "esse", "anim", "non"]
}
];
function filter(key) {
return arr.filter((obj) => {
const regex = new RegExp(`${key}`, 'gi');
const matches = obj.tags.filter((tag) => tag.match(regex))
if(matches.length > 0) {
return true;
}
});
}
console.log(filter("a"));
Upvotes: 3