简体   繁体   English

javascript - 在数组上使用过滤器和匹配方法来查找完全匹配

[英]javascript - use the filter and match methods on an array to find exact matches

I'm using a filter function to find JSON objects in an array called arrayList , which contains for example:我正在使用过滤器函数在名为arrayList的数组中查找 JSON 对象,其中包含例如:

[
 {
   "name": "Markdown",
   "extension": "(.md)"
 },
 {
   "name": "MultiMarkdown",
   "extension": "(.mmd, .txt)"
 }
]

I'm using the following code to search on the name field and find a match for an object with a certain name:我正在使用以下代码搜索name字段并找到具有特定名称的对象的匹配项:

findFormat = (name) => {
  let format = arrayList.filter(function (el) {
    let pattern = new RegExp(name);
    return el.name.match(pattern);
  });
  return format.name
}

So if I'm searching for an object that has the name "Markdown" then this string gets passed via the name parameter in the function above, and the RegExp expression resolves to /Markdown/ .因此,如果我正在搜索名称为“Markdown”的对象,则该字符串通过上面函数中的name参数传递,并且RegExp表达式解析为/Markdown/

For the filter function itself, I've implemented the polyfill described at the bottom of the MDN documentation :对于过滤器功能本身,我已经实现了MDN 文档底部描述的polyfill

if (!Array.prototype.filter)
        Array.prototype.filter = function(func, thisArg) {
            'use strict';
            if ( ! ((typeof func === 'Function') && this) )
                throw new TypeError();

            var len = this.length >>> 0,
                res = new Array(len), // preallocate array
                c = 0, i = -1;
            if (thisArg === undefined)
                while (++i !== len)
                    // checks to see if the key was set
                    if (i in this)
                        if (func(t[i], i, t))
                            res[c++] = t[i];
                        else
                            while (++i !== len)
                                // checks to see if the key was set
                                if (i in this)
                                    if (func.call(thisArg, t[i], i, t))
                                        res[c++] = t[i];

            res.length = c; // shrink down array to proper size
            return res;
        };

For the regular expression I'm not using any special flags like i because I want to find an exact match for "Markdown".对于正则表达式,我没有使用像i这样的任何特殊标志,因为我想找到“Markdown”的完全匹配项。 However it keeps returning instead MultiMarkdown .但是它不断返回MultiMarkdown I had thought that the filter function above found only exact matches, and not substrings.我原以为上面的过滤器函数只能找到完全匹配,而不是子字符串。

Question : is there a way I can filter for only exact matches, using the filter and match methods?问题:有没有一种方法可以使用filtermatch方法仅过滤完全匹配? Wouldn't the polyfill above return an exact match?上面的 polyfill 不会返回完全匹配吗?

There's a few misunderstandings you have:你有几个误解:

  1. Regular expressions is used for matching strings that match a certain pattern.正则表达式用于匹配匹配特定模式的字符串。 It's a powerful thing but I'd say it's not the best tool to use if you're trying to find an exact match.这是一个强大的东西,但我想说如果你试图找到一个完全匹配的东西,它不是最好的工具。 In that case, you could just use the strict equality operator === .在这种情况下,您可以只使用严格相等运算符=== (If you did want to use regex, you could add the ^ and the $ before the regex to match the first and last characters of the line eg /^Markdown$/ would only match Markdown ) (如果您确实想使用正则表达式,则可以在正则表达式之前添加^$以匹配该行的第一个和最后一个字符,例如/^Markdown$/只会匹配Markdown
  2. Polyfills implement missing features of the Javascript standard (EcmaScript) and Array.prototype.filter is implemented in all major browsers do you don't need to implement it. Polyfills 实现了 Javascript 标准 (EcmaScript) 缺少的功能, Array.prototype.filter在所有主要浏览器中都实现了,你不需要实现它。

See the example below on how to match name strictly.有关如何严格匹配name请参见下面的示例。

 const array = [{ "name": "Markdown", "extension": "(.md)" }, { "name": "MultiMarkdown", "extension": "(.mmd, .txt)" } ] const criteria = 'Markdown'; const result = array.filter(item => item.name === criteria); console.log('result', result);

You don't need RegEx here and probably shouldn't use it as it will be slower.您在这里不需要 RegEx 并且可能不应该使用它,因为它会更慢。 However, that is not the issue.然而,这不是问题。 The issue is that new RegExp(name);问题是new RegExp(name); will create a RegEx that does a contains search.将创建一个执行包含搜索的正则表达式。 See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions .请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

I would recommend changing我会建议改变

let pattern = new RegExp(name);
return el.name.match(pattern);

to

return el.name === name;

Check for equality if you want exact match如果您想要完全匹配,请检查是否相等

  let format = arrayList.filter(function (el) {    
    return el.name === name;
  });

Or if you want case insensitive then normalize the cases:或者,如果您想要不区分大小写,则对案例进行规范化:

  let format = arrayList.filter(function (el) {    
    return el.name.toLowerCase() === name.toLowerCase();
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找并返回Javascript数组中的完全匹配项(重复项) - Find and return exact matches (duplicates) in Javascript Array Javascript:数组完全匹配 - Javascript: Array exact match 如何过滤数组以仅在 Google Apps 脚本/Javascript 中完全匹配 - How to filter array for only exact match in Google Apps Script/Javascript 如何在 JavaScript 中的数组中找到精确匹配的 substring? - How do I find an exact substring match in an array in JavaScript? 在数组中找到确切的数字匹配? - Find exact number match in array? JavaScript 如何在不提供与 object 值匹配的确切搜索值的情况下查找 object 数组的数据 - JavaScript how to find data of array of object without giving exact search value that matches with value of object Javascript 字符串包括没有进一步匹配的完全匹配 - Javascript String Includes Exact Match without further matches Javascript 搜索/过滤嵌套循环搜索和大量文本的完全匹配 - Javascript Searches/ Filter nested looping search and exact matches with lots of text 精确字符串匹配文件名数组 JavaScript/Nodejs - Exact String Match FileName Array JavaScript/Nodejs Javascript如何在属性匹配列表时使用json数组上的array.filter返回整个数组 - Javascript how use array.filter on json array to return whole array if property matches a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM