Home > Software engineering >  Search if a String has a subset string present in array of object javascript
Search if a String has a subset string present in array of object javascript

Time:01-05

Looking for the optimal solution to find a string inside an array of objects.

Let's say I have a variable that holds a result which I get from an API call

let result = "485178485451478"

I have to search the above result in the below array of objects & see if the substring in the array matches the result. If the result matches I simply want to return true.

const arrayCode = [
      {
        "code": "2150"
      },
      {
        "code": "4857"
      },
      {
        "code": "5046"
      },
      {
        "code": "4851"
      },
      {
        "code": "4154"
      },
      {
        "code": "9654"
      },
      {
        "code": "1254"
      },
      {
        "code": "9562"
      },
      {
        "code": "1457"
      },
      {
        "code": "6479"
      }]

So here in the above problem if I write a code, it should return me an index of 3.

Below is the basic code which I wrote to get the solution. But what if the array length is too long? Looking for the optimal solution. Thanks

Below is the code:

let result = "485178485451478"
let index = 0
for(let i= 0; i< arrayCode.length;i  ){
    let flag = result.indexOf(arrayCode[i].code);
    if(flag===0){
        index = i;
        break;
    }
}

console.log(index)

CodePudding user response:

The some function will iterate only until it finds the first occurrence, so you could use along with the includes function:

const included = (element) => result.includes(element.code);
console.log(arrayCode.some(included));

CodePudding user response:

here is What I would do:

let index = 0
arrayCode.forEach((e, indx) => {if(result.indexOf(e.code) == 0)index = indx;});
console.log(index)

Hope to help!

  • Related