Javascript 使用Underscorejs,如何查找一个数组是否包含另一个数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14221683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:04:48  来源:igfitidea点击:

With Underscorejs, how to find whether an array contains another array?

javascriptunderscore.js

提问by epascarello

I have this

我有这个

var matches = bookmarks.filter(function(x) {
    return _.contains(x.get("tags"), 'apple');
});

Which will return the bookmark objects that have the apple tags

这将返回具有苹果标签的书签对象

I want to put an array there instead to pull and all the bookmarks that have the matching values, similar to this

我想在那里放一个数组来拉取所有具有匹配值的书签,类似于这个

var matches = bookmarks.filter(function(x) {
    return _.contains(x.get("tags"), ['apple','orange']);
});

This doesn't work, any way to get it to work?

这不起作用,有什么办法让它起作用吗?

EDIT: Im sorry, bookmarks is a collection and im trying to return the models that have the apple and orange tags

编辑:对不起,书签是一个集合,我试图返回带有苹果和橙色标签的模型

回答by epascarello

If tags is a string, your code it would be

如果标签是一个字符串,你的代码就是

return _.indexOf(x.get("tags"), ['apple','orange']) > -1;

Example with indexOf : jsFiddle

indexOf 示例:jsFiddle

If tags is an array, you can use intersection

如果标签是一个数组,你可以使用交集

return _.intersection(['apple','orange'], x.get("tags")).length > 0;

Example with intersection: jsFiddle

带交点的示例:jsFiddle

回答by pimvdb

There doesn't seem to be a function for that in underscore. However, you can easily combine other functions to accomplish this:

下划线中似乎没有该功能。但是,您可以轻松地结合其他功能来完成此操作:

_.mixin({
  containsAny: function(arr, values) {
    // at least one (.some) of the values should be in the array (.contains)
    return _.some(values, function(value) {
      return _.contains(arr, value);
    });
  }
});