Filter Substring from JSON in JQuery

JSON –

"offers": [           
    {
        "loanType": "432321CMP",
    },
    {
        "loanType": "788407CMP",
    },
    {
        "loanType": "97934OOW",
    },
    {
        "loanType": "8293EWC-AS",
    },
    {
        "loanType": "6653EWC-AS",
    }
]

I want to filter data basis the substring in the end ["EWC-AS", "CMP"]

    myArrayFiltered = offers.filter(function(v) {
        return (["EWC-AS"].indexOf(v.loanType)) > -1;
    });

if I pass on the exact value to match it works, but for subtring it does not.

Thanks in Advance for the help

10 thoughts on “Filter Substring from JSON in JQuery”

  1. Array.prototype.indexOf() looks for exact matches, not substrings. Use find() to search an array using a callback function so you can specify how to match it. And use String.prototype.includes() to test for a substring match.

    let offers = [{
        "loanType": "432321CMP",
      },
      {
        "loanType": "788407CMP",
      },
      {
        "loanType": "97934OOW",
      },
      {
        "loanType": "8293EWC-AS",
      },
      {
        "loanType": "6653EWC-AS",
      }
    ];
    
    let codes = ["EWC-AS", "CMP"];
    let myArrayFiltered = offers.filter(o => codes.find(s => o.loanType.includes(s)));
    
    console.log(myArrayFiltered);
    Reply
  2. You can filter it by using filter in combination with find and endsWith to check if the substring is at the end of the string.

    const codes = ["EWC-AS", "CMP"];
    const myArrayFiltered = bla.offers.filter(x => codes.find(z => x.loanType.endsWith(z)));
    
    const bla = {
      "offers": [{
          "loanType": "432321CMP",
        },
        {
          "loanType": "788407CMP",
        },
        {
          "loanType": "97934OOW",
        },
        {
          "loanType": "8293EWC-AS",
        },
        {
          "loanType": "6653EWC-AS",
        },
        {
          "loanType": "EWC-AS6653",
        }
      ]
    };
    
    const codes = ["EWC-AS", "CMP"];
    const myArrayFiltered = bla.offers.filter(x => codes.find(z => x.loanType.endsWith(z)));
    console.log(myArrayFiltered);
    Reply

Leave a Comment