Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to search a Javascript array for partial matches?

Tags:

javascript

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.

like image 587
Damo Avatar asked Nov 02 '25 20:11

Damo


1 Answers

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.includes("Man"))
console.log(fruitsWithMan); // returns array

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

const hasFruitWithMan = fruits.some(x => x.includes("Man"));
console.log(hasFruitWithMan); // return boolean
like image 150
Jamiec Avatar answered Nov 04 '25 10:11

Jamiec