使用另一个数组过滤数组

时间:2017-04-20 06:36:58

标签: javascript arrays ejs

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。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

使用reduceincludes,你可以这样:



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

答案 2 :(得分:0)

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



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; }