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

I have 2 arrays - Array1 and Array2. I want to filter Array2 by using Array1 such that my output comes as - [ { name: name1 , id: 1 }, { name: name2 , id: 2 }]. I tried like this - var ids = _.pluck(_.filter(Array2, a => _.contains(Array1, a.id)), 'id'); but problem with this is it's only giving one thing at a time means I can only get either name or id or location or address at a time but I want to filter name and id both at a time.

Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
abhjt
  • 402
  • 4
  • 11
  • 25

3 Answers3

1

Loop over the second array and for each item look if the first contains it. If contains, includes will return true and that element will be in a new array.

Be aware this works only in 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);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Instead of having to .filter and then .map it, just use .reduce.

Using reduce and includes, you can have something like this:

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)

Note, that you can use indexOf instead of includes if needing to support older browsers.

tanmay
  • 7,761
  • 2
  • 19
  • 38
0

You could use a hash table for faster check if the wanted names are in the item for filtering.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392