JavaScript的筛选器,在查询为“A C”时返回与“A B C”匹配的结果。

huangapple go评论76阅读模式
英文:

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函数与正则表达式结合使用。由于你对单词JohnDoe感兴趣,正则表达式/\b(?:John|Doe)\b/在字符串上执行,如果字符串中存在JohnDoe中的任何一个单词,将返回结果。

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(`[{
		&quot;id&quot;: 1,
		&quot;full_name&quot;: &quot;John &quot;
	},
	{
		&quot;id&quot;: 2,
		&quot;full_name&quot;: &quot;John T Doe&quot;
	},
	{
		&quot;id&quot;: 3,
		&quot;full_name&quot;: &quot;John T. Doe&quot;
	},
	{
		&quot;id&quot;: 4,
		&quot;full_name&quot;: &quot;Jon Dough&quot;
	}
]`);

console.log(arr.filter(element =&gt; element.full_name.match(/\b(?:John|Doe)\b/)));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月11日 06:52:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223070.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定