英文:
JavaScript filter that returns a match for "A B C" when query is "A C"
问题
给定一个JSON对象数组:
[
{
"id": 1,
"full_name": "约翰·多"
},
{
"id": 2,
"full_name": "约翰·T·多"
},
{
"id": 3,
"full_name": "约翰·T·多"
},
{
"id": 4,
"full_name": "乔恩·道"
}
]
不使用for循环,可以过滤此列表,以便在给定搜索查询为“约翰多”时,返回一个由记录1-3组成的过滤数组作为匹配项,但不包括4。
当搜索查询为“约翰多”时,如果对象集合中出现“约翰”或“多”,则存在匹配。
英文:
Given a JSON array of objects:
`[
{
"id": 1,
"full_name": "John Doe"
},
{
"id": 2,
"full_name": "John T Doe"
},
{
"id": 3,
"full_name": "John T. Doe"
},
{
"id": 4,
"full_name": "Jon Dough"
}
]`
Without doing a for loop, is it possible to filter this list so that given a search query of "John Doe", it returns a filtered array consisting of records 1-3 as matches but not 4?
When the search query is "John Doe" a match exists if either "John" or "Doe" appears in the object collection.
答案1
得分: 1
在你的特定情况下,你可以利用数组对象的.filter
函数与正则表达式结合使用。由于你对单词John
和Doe
感兴趣,正则表达式/\b(?:John|Doe)\b/
在字符串上执行,如果字符串中存在John
或Doe
中的任何一个单词,将返回结果。
let arr = JSON.parse(`[{
"id": 1,
"full_name": "John "
},
{
"id": 2,
"full_name": "John T Doe"
},
{
"id": 3,
"full_name": "John T. Doe"
},
{
"id": 4,
"full_name": "Jon Dough"
}
]`);
console.log(arr.filter(element => element.full_name.match(/\b(?:John|Doe)\b/)));
英文:
In your specific case you can utilize the array objects .filter
function in combination with a regular expression. As you're interested in the words John
and Doe
, the regular expression /\b(?:John|Doe)\b/
executed on a string will return a result if either the word John or Doe are present.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let arr = JSON.parse(`[{
"id": 1,
"full_name": "John "
},
{
"id": 2,
"full_name": "John T Doe"
},
{
"id": 3,
"full_name": "John T. Doe"
},
{
"id": 4,
"full_name": "Jon Dough"
}
]`);
console.log(arr.filter(element => element.full_name.match(/\b(?:John|Doe)\b/)));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论