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.
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.
Share Improve this question asked Jan 13, 2022 at 10:41 DamoDamo 737 bronze badges3 Answers
Reset to default 7You 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
You could filter the array this way :
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.filter(fruit => fruit.includes("Man")));
["Banana", "Orange", "Apple", "Mango"].some(fruit => fruit.includes("Man"));