针对所有另一个数组过滤数组

Joh*_*eri 3 javascript arrays loops for-loop angularjs

$ scope.categories阵列正被从在AngularJS多选择元件填充.

$scope.categories = ["Adventure", "Strategy"]
Run Code Online (Sandbox Code Playgroud)

我需要将此数组与下面的items数组中的categories数组进行比较:

$scope.items = [
    {
        title: "Star Wars",
        categories: ["Adventure"]
    }, {
        title: "Star Search",
        categories: ["Adventure", "Strategy"]
    }, {
        title: "Star Trek",
        categories: ["Adventure", "Family"]
    }, {
    title: "Star Wars",
    categories: ["Family", "Strategy"]
}];
Run Code Online (Sandbox Code Playgroud)

在这两个值$ scope.categories需要匹配在相同的值$ scope.items.categories,对象被推向一个输出阵列.

生成的$ scope.filtered数组为(项1):

{
  title: "Star Search",
  categories: ["Adventure", "Strategy"]
}
Run Code Online (Sandbox Code Playgroud)

我有逻辑,直到循环需要重申......但是如何?

  1. 我循环遍历$ scope.categories
  2. 然后循环遍历$ scope.items
  3. 然后循环遍历每个对象的$ scope.item.categories数组.
  4. 然后我比较$ scope.categories对价值价值$ scope.item.categories

    for (var i = 0; i < categories.length; i++) {
      for (var j = 0; j < items.length; j++) {
        for (var k = 0; k < items[j].categories.length; k++) {
          if(categories[i] == items[j].categories[k]) {
            console.log("The value of " + categories[i] + ", matches " + items[j].categories[k]);
          } else {
            console.log("The value of " + categories[i] + ", is not a match");
          }
        }
      }
    }
    
    Run Code Online (Sandbox Code Playgroud)

这是一个JSbin示例

Ami*_*mit 6

这真的很简单:

var filtered = items.filter(function(i) {
  return categories.every(function(c) {
    return i.categories.indexOf(c) >= 0
  })
})
Run Code Online (Sandbox Code Playgroud)

Array.prototype.filter迭代一个数组并为每个项调用一个回调函数.回调函数返回true的每个项都包含在结果数组中.

Array.prototype.every 迭代一个数组并为每个项调用一个回调函数,如果所有项的回调返回true则返回true,否则返回false.

在这个用例中,我们过滤items数组,当所有类别"传递" every回调条件时,过滤器回调返回true ,即条目类别包含current(c)类别.

(这是固定的JSBin)