最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

How best to search a Javascript array for partial matches? - Stack Overflow

matteradmin7PV0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 7

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

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"));
Post a comment

comment list (0)

  1. No comments so far