Filter array based on an array of index

The simplest way is to use _.map on arr2, like this

console.log(_.map(arr2, function (item) {
  return arr1[item];
}));
// [ 77, 33, 8 ]

Here, we iterate the indexes and fetching the corresponding values from arr1 and creating a new array.


Equivalent to the above, but perhaps a bit more advanced, is to use _.propertyOf instead of the anonymous function:

console.log(_.map(arr2, _.propertyOf(arr1)));
// [ 77, 33, 8 ]

If your environment supports ECMA Script 6's Arrow functions, then you can also do

console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]

Moreover, you can use the native Array.protoype.map itself, if your target environment supports them, like this

console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]

You are returning index, so in your case 0 treated as false. So you need to return true instead

res = _.filter(arr1, function(value, index){
    if(_.contains(arr2, index)){
        return true;
    }
});

or just return _.contains()

res = _.filter(arr1, function(value, index){
   return _.contains(arr2, index);
});

_.contains returns a boolean. You should return that from the filter predicate, rather than the index because 0 is a falsy value.

res = _.filter(arr1, function(value, index)) {
  return _.contains(arr2, index);
});

As an aside, JavaScript arrays have a native filter method so you could use:

res = arr1.filter(function(value, index)) {
  return _.contains(arr2, index);
});

for me the best way to do this is with filter.

let z=[10,11,12,13,14,15,16,17,18,19]

let x=[0,3,7]

z.filter((el,i)=>x.some(j => i === j))
//result
[10, 13, 17]