【问题标题】:Filter array by content?按内容过滤数组?
【发布时间】:2018-12-23 03:30:06
【问题描述】:

我正在尝试过滤一个非基于对象的数组,我需要过滤器来简单地检查数组的每一部分是否有特定的字符串。

假设我有这个数组:

["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]

我需要做的是以某种方式收集数组,以便我得到一个新数组,其中只包含那些以 http://mywebsite.com 而不是 http://yourwebsite.com 开头的数组

总结一下:["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"]

进入这个["http://mywebsite.com/search", "http://mywebsite.com/search"]

【问题讨论】:

  • 所以你想过滤一个数组...你试过使用.filter方法吗?

标签: javascript jquery arrays filter filtering


【解决方案1】:

您可以使用String的.filter()和.startsWith()方法过滤数组。

来自文档:

startsWith()方法判断一个字符串是否以指定字符串的字符开头,根据需要返回真或假。

演示:

let data = ["http://mywebsite.com/search",
            "http://mywebsite.com/search",
            "http://yourwebsite.com/search"];

let result = data.filter(s => s.startsWith('http://mywebsite.com/'));

console.log(result);

正如您在评论中提到的那样;如果你想检查多个字符串,那么你可以试试这个:

let data = ["http://mywebsite.com/search",
            "http://mywebsite.com/find",
            "http://yourwebsite.com/search",
            "http://yourwebsite.com/find"];

let strToMatch = ["http://mywebsite.com/search", "http://mywebsite.com/find"];

let result = data.filter(s1 => strToMatch.some(s2 => s2.startsWith(s1)));

console.log(result);

文档:

【讨论】:

  • 谢谢,这很好用。我还想知道是否可以扭转这个概念,以便我选择过滤的内容被过滤掉,因为目前我过滤的内容是唯一保留的内容。这样你上面的建议就会导致一个数组,其中 mywebsite.com 被排除在外。
  • @user10083700 是的,只是从回调中返回否定值,即data.filter(s => !s.startsWith('http://mywebsite.com/'))
  • 我可以在里面有多个参数吗?像这样的东西:arr.filter(s => s.startsWith('mywebsite.com/search, mywebsite.com/find'));
  • @user10083700 我已经更新了我的答案。此方法中没有对多重字符串的本机支持。为此,您必须使用数组。
【解决方案2】:

使用数组 filter() 方法 您可以创建一个简单的函数并传递该字符串数组并检查您想要的内容是否存在

var yourString = ["http://mywebsite.com/search", "http://mywebsite.com/search", "http://yourwebsite.com/search"];

function specificString(yourString ) {
    return yourString === "http://mywebsite.com/search";
}
console.log(specificString(yourString));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 2016-08-09
    • 2017-11-03
    • 2013-09-21
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多