Home > Mobile >  Filter 2d array by matching string
Filter 2d array by matching string

Time:02-10

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:

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

CodePudding user response:

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; }

  • Related