SDK
SDK

Reputation: 1518

How to filter value based on the nested array value?

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

Answers (1)

BadPiggie
BadPiggie

Reputation: 6359

Search for Full Word

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"));

Search for matches

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

Related Questions