Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter 2d array by matching string

I have the following array below and looking to match all objects that match the string "en-GB". My current implementation results in "Cannot use ‘in’ operator to search for ‘en’ in en-GB"

Array:

const filtData = [
  [
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "es",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "dk",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "sp",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "it",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "en",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "uk",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
  ],
];

JS filter:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const res = filtData.map((el) => el.filter((a) => a.descriptions.attrs.lang.some((o) => "en-GB" in o)));
console.log(filtData);

>Solution :

You need to compare the value.

const
    filtData = [[{ descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "es" } } }, { descriptions: { attrs: { lang: "dk" } } }], [ { descriptions: { attrs: { lang: "sp" } } }, { descriptions: { attrs: { lang: "en-GB" } } }, { descriptions: { attrs: { lang: "it" } } }], [{ descriptions: { attrs: { lang: "en" } } }, { descriptions: { attrs: { lang: "uk" } } }, { descriptions: { attrs: { lang: "en-GB" } } }]],
    result = filtData.map(a =>
        a.filter(({ descriptions: { attrs: { lang } } }) => lang === "en-GB")
    );
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading