0

How to filter the following array with another array values?

  const GuideTabs = [
    { id: 0, label: 'Highlights', analyticsCategory: 'Highlights' },
    { id: 1, label: 'Labor & Employment', analyticsCategory: 'Labor & Employment' },
    { id: 2, label: 'Culture', analyticsCategory: 'Culture' },
    { id: 3, label: 'Holidays', analyticsCategory: 'Holidays' },
  ]

I want to filter this array with the following array to return only the existing data

 const gtabs = ['Culture, Holidays']
  const arr = GuideTabs.filter(function(item){
    return gtabs.indexOf(item.id) === -1
  })

But it returns all the 4 array item in GuideTabs all the time, But it should return 2,3 items from GuideTabs array

  const GuideTabs = [
    { id: 0, label: 'Highlights', analyticsCategory: 'Highlights' },
    { id: 1, label: 'Labor & Employment', analyticsCategory: 'Labor & Employment' },
    { id: 2, label: 'Culture', analyticsCategory: 'Culture' },
    { id: 3, label: 'Holidays', analyticsCategory: 'Holidays' },
  ]
  const gtabs = ['Culture, Holidays']
  const arr = GuideTabs.filter(function(item){
    return gtabs.indexOf(item.id) === -1
  })
  
  console.log(arr)

2
  • 1
    const gtabs = ['Culture, Holidays'] this is an array with one element. I guess this should be const gtabs = ['Culture', 'Holidays'] Commented Jun 10, 2021 at 12:11
  • 1
    return gtabs.indexOf(item.label) != -1 ? Commented Jun 10, 2021 at 12:12

2 Answers 2

3

You need to use

gtabs.includes(obj.label))

Because you are going to compare with gTabs that contain strings i.e "Culture", "Holidays"

const GuideTabs = [
  { id: 0, label: "Highlights", analyticsCategory: "Highlights" },
  {
    id: 1,
    label: "Labor & Employment",
    analyticsCategory: "Labor & Employment",
  },
  { id: 2, label: "Culture", analyticsCategory: "Culture" },
  { id: 3, label: "Holidays", analyticsCategory: "Holidays" },
];

const gtabs = ["Culture", "Holidays"];

const result = GuideTabs.filter((obj) => gtabs.includes(obj.label));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

You can use some along with filter too.

const result = GuideTabs.filter((tab) => gtabs.some((guideTab) => guideTab === tab.label));

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.