4
 data:[
        {
           id:1,
           tags:['TagA','TagB','TagC']
         },
         {
           id:2,
           tags:['TagB','TagD']
         },
         {
            id:3,
            tags:['tagE','tagC']
         }
      ]

filterCondition:{tags:['TagA','TagB']}

Expected Output: [
                   {
                     id:1,
                     tags:['TagA','TagB','TagC']
                   },
                   {
                     id:2,
                     tags:['TagB','TagD']
                   }
                 ]

Is there a possible way to achieve this in typescript using filter method? It is possible when tags field is not an array but when it is in array the code breaks.

I tried but it fails:

   data.filter(o => Object.keys(filterCondition).every(k => filterCondition[k].some(f => o[k] === f)));
1
  • typescript is superset of js, so js solution will work because it is js Commented Dec 17, 2018 at 12:40

2 Answers 2

3

you can use filter and includes

const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];
      
const filterData = tag => data.filter(d => tag.some(t => d.tags.includes(t)));

console.log(filterData(['TagA', 'TagB']));

Little edit in the form of conditionArray mentioned:

    let filterArray={tags:['TagA','TagB']}

    const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];

    output= data.filter(o => Object.keys(filterArray).every(d => filterArray[d].some(t => o[d].includes(t))));
Sign up to request clarification or add additional context in comments.

4 Comments

I want to filter it based on 'filterCondition' array, hence includes wont work when filterCondition:{tags:['tagA','tagB']}
it is based on that array as you described in question, please explain what you mean and give example
Artyom Amiryan ,please see the edited example. If any of the tags in the condition array is present in the object, then that object should be there in the ouput
@RishabhBharatGada I have updated my example, please check if is it what you need ?
2

const s = {
  data: [{
      id: 1,
      tags: ['TagA', 'TagB', 'TagC']
    },
    {
      id: 2,
      tags: ['TagB', 'TagD']
    },
    {
      id: 3,
      tags: ['tagE', 'tagC']
    }
  ],
  filterCondition: {
    tags: ['TagA', 'TagB']
  }
};

console.log(s.data.filter(a => s.filterCondition.tags

  .some(s => a.tags.join(',').includes(s))));

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.