I have a first array of values and a second array of indexes. I would like to filter the first array and return only values that have indexes in the second array.
So, given:
arr1 = [4775453877338112, 5901353784180736, 6605041225957376]
arr2 = [0,2]
I would like to return:
output = [4775453877338112, 6605041225957376]
Thanks. For bonus points, why doesn't the following work?
var output = arr1.filter( (item) => arr1.indexOf(item) in arr2 === true )
Apologies if this simple question is a duplicate of this: Filter array based on an array of index, but the underscore is throwing me off.
For bonus points, why doesn't the following work?
Because you are checking if the index is present in arr2, not the item itself.
Just simply use a map
var output = arr2.map( s => arr1[s] );
Demo
var arr1 = [4775453877338112, 5901353784180736, 6605041225957376];
var arr2 = [0,2];
var output = arr2.map( s => arr1[s] );
console.log( output );
var output = arr1.filter( (item) => arr1.indexOf(item) in arr2 === true ) indexOf returns index of element not a boolean. You could use new Array.prototype.includes or test for value to be -1
Also if order is the same you could loop over index array instead.
const arr1 = [4775453877338112, 5901353784180736, 6605041225957376]
const arr2 = [0,2]
const output = arr2.map(i => arr1[i])
console.log(output)
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