-4

I have an array that contains the tags values, now how to return all the respective tag objects that contain a search tag ??

I have an array like this:

[
    {"tags": ["a"]},
    {"tags": ["a","b"]},
    {"tags": ["a","c"]},
    {"tags": ["a","b","c"]},
    {"tags": ["a","d"]}
] 

For "a" it should return all the objects

For "b" it should return 2 objects (index 1 and index 4)

For "c" it should return 2 objects (index 2 and index 3)

Nagasai M
  • 1
  • 1
  • Welcome to SO. You might find reading the site [help section](https://stackoverflow.com/help) useful when it comes to [asking a good question](https://stackoverflow.com/help/how-to-ask), and this [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist). Code that you've worked on to solve the problem should include a [mcve], and be included in your question. – Andy Sep 06 '21 at 08:14
  • 1
    Iterate them and look through the tags? Please show us what you tried. If you need a hint: `filter` and `includes`. – Bergi Sep 06 '21 at 08:14
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 06 '21 at 08:20
  • [Edit] your post and clarify the search requirements. Should the input `"a"` return all objects because the string `"a"` is exactly included in all arrays, or because `"a"` is a substring of any string in all arrays? – Sebastian Simon Sep 06 '21 at 08:22

1 Answers1

4

Perhaps you can use this one (using Array#filter and Array#includes):

const search = str => {
  const tags = [
    { tags: ['a'] },
    { tags: ['a', 'b'] },
    { tags: ['a', 'c'] },
    { tags: ['a', 'b', 'c'] },
    { tags: ['a', 'd'] }
  ]

  return tags.filter(x => x.tags.includes(str))
}

console.log(search('b'))

Note that this searches with strict casing.

lejlun
  • 4,140
  • 2
  • 15
  • 31
Karma Blackshaw
  • 880
  • 8
  • 20