1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.