Home > Software design >  How best to search a Javascript array for partial matches?
How best to search a Javascript array for partial matches?

Time:01-13

I'm very new to Javascript and I expect there is a simple answer, but how can you search a Javascript array for a partial match?

So if I have an array such as:

const fruits = ["Banana", "Orange", "Apple", "Mango"];

I know I can easily check if the array contains something using:

fruits.includes("Mango");

But what if I want to know whether an array contains a value that partially matches a certain sequence of characters?

For example, if I want to know if the above array includes an entry that has the string "Man" in it.

CodePudding user response:

You can use filter if you want to find multiple objects might match, or find if you only want one, or if you just want to know if it exists at all use some

const fruits = ["Banana", "Orange", "Apple", "Mango"];

const fruitsWithMan = fruits.filter(x => x.indexOf("Man") > -1)
console.log(fruitsWithMan); // returns array

const oneFruitWithMan = fruits.find(x => x.indexOf("Man") > -1)
console.log(oneFruitWithMan); // returns single item

const hasFruitWithMan = fruits.some(x => x.indexOf("Man") > -1);
console.log(hasFruitWithMan); // return boolean

CodePudding user response:

You could filter the array this way :

const fruits = ["Banana", "Orange", "Apple", "Mango"];

console.log(fruits.filter(fruit => fruit.includes("Man")));

CodePudding user response:

["Banana", "Orange", "Apple", "Mango"].some(fruit => fruit.includes("Man"));
  •  Tags:  
  • Related