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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With