Filter Substring from JSON in JQuery

Viewed 97

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 substring it does not.

2 Answers

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

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

Related