Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array based on an array of index

First I apologize if it's a duplicate (I searched but did not find this simple example...), but I want to select elements of arr1 based on the index in arr2:

arr1 = [33,66,77,8,99]
arr2 = [2,0,3] 

I am using underscore.js but the 0 index is not retrieved (seems to be considered as false):

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

Which returns:

# [77, 8]

How could I fix this, and is there a simpler way to filter using an array of indexes? I am expecting the following result:

# [77, 33, 8]
like image 512
Colonel Beauvel Avatar asked Oct 19 '15 10:10

Colonel Beauvel


1 Answers

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]
like image 173
Luis Tiago Flores Cristóvão Avatar answered Oct 16 '22 15:10

Luis Tiago Flores Cristóvão