2017-04-20 73 views
1
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。使用另一個陣列過濾數組

+0

試'Array2.filter(函數(項目){返回Array1.indexOf(item.name)})' – gurvinder372

+0

的[減去陣列 - 的javascript]可能的複製(HTTP:// stackoverflow.com/questions/21509474/subtract-arrays-javascript) – Alessandro

回答

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

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

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