【问题标题】:Filtering an array by using another array使用另一个数组过滤数组
【发布时间】:2017-09-16 15:23:39
【问题描述】:
Array1 = [ name1, name2];
Array2 = [ { name: name1 , id: 1, location: xyz, address: 123 },
           { name: name2 , id: 2, location: abc, address: 456 },
           { name: name3 , id: 3, location: def, address: 234 },
           { name: name4 , id: 4, location: ghi, address: 789 }
         ];

我有 2 个数组 - Array1 和 Array2。我想使用 Array1 过滤 Array2,这样我的输出就变成了 - [ { name: name1 , id: 1 }, { name: name2 , id: 2 }]。我试过这样 - var ids = _.pluck(_.filter(Array2, a => _.contains(Array1, a.id)), 'id'); 但问题是它一次只提供一件事意味着我一次只能获取名称或 ID 或位置或地址,但我想一次过滤名称和 ID。

【问题讨论】:

标签: javascript arrays ejs


【解决方案1】:

遍历第二个数组,并为每个项目查找第一个是否包含它。如果包含,includes 将返回 true,并且该元素将位于新数组中。

请注意,这只适用于 ES6

var arr1 = [ 'A', 'B'];
var arr2 = [ { name: 'A' , id: 1,address: 123 },
           { name: 'B' , id: 2, address: 456 },
           { name: 'C' , id: 3, address: 234 },
           { name: 'D' , id: 4,address: 789 }
         ];
         
var newArr = arr2.filter(item => arr1.includes(item.name)).map(item => ({ name: item.name, id: item.id}));

console.log(newArr);

【讨论】:

    【解决方案2】:

    不必.filter,然后是.map,只需使用.reduce。

    使用reduce 和includes,你可以有这样的东西:

    var Array1 = ["name1", "name2"];
    var Array2 = [{
        name: "name1",
        id: 1,
        location: "xyz",
        address: 123
      },
      {
        name: "name2",
        id: 2,
        location: "abc",
        address: 456
      },
      {
        name: "name3",
        id: 3,
        location: "def",
        address: 234
      },
      {
        name: "name4",
        id: 4,
        location: "ghi",
        address: 789
      }
    ];
    
    var result = Array2.reduce((arr, cur) => {
      if(Array1.includes(cur.name)) {
        arr.push({
          name: cur.name,
          id: cur.id
        })
      }
      return arr
    }, [])
    
    console.log(result)

    请注意,如果需要支持旧版浏览器,您可以使用indexOf 而不是includes。

    【讨论】:

      【解决方案3】:

      您可以使用哈希表来更快地检查想要的名称是否在要过滤的项目中。

      var array1 = ['name1', 'name2'],
          array2 = [{ name: 'name1', id: 1, location: 'xyz', address: 123 }, { name: 'name2', id: 2, location: 'abc', address: 456 }, { name: 'name3', id: 3, location: 'def', address: 234 }, { name: 'name4', id: 4, location: 'ghi', address: 789 }],
          result = array2.filter(function (a) {
              var hash = Object.create(null);
              a.forEach(function (k) { hash[k] = true; });
              return function (b) { return hash[b.name]; };
          }(array1));
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 2017-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-24
        相关资源
        最近更新 更多