Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array by array of indexes

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.

like image 492
rvictordelta Avatar asked Apr 18 '26 15:04

rvictordelta


2 Answers

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 );
like image 166
gurvinder372 Avatar answered Apr 21 '26 05:04

gurvinder372


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)
like image 20
Yury Tarabanko Avatar answered Apr 21 '26 05:04

Yury Tarabanko