1

I want to filter this array by index?

arr = [1,2,3,4,5,6];

I am trying to use

arr.filter(x => x === [2,3])

but it does not seems to work?

I want only [2, 3]rd index?

0

1 Answer 1

3

You need map here rather than filter:

arr = [11,22,33,44,55,66];
indexes = [2,3]
result = indexes.map(i => arr[i])
console.log(result)

Note that this returns values in the indexes order, but if indexes are unsorted and you need values in the source order, then you indeed need filter. Consider:

arr = [11,22,33,44,55,66];
indexes = [4,2]

result1 = indexes.map(i => arr[i])
result2 = arr.filter((_,i) => indexes.includes(i))

console.log(result1)
console.log(result2)

Sign up to request clarification or add additional context in comments.

3 Comments

The only answer that didn't get misled by the OP's use of filter, resulting in a very obvious and clean solution.
@Cerbrus: they are actually different, depends on what exactly the OP wants.
Considering the simple sample data, I doubt the ordering matters, but ok. (Even then, if sorting matters, it's probably more efficient to just sort the indexes array and then map)