14

This works, but I'm wondering if there is a better way to filter by index:

a = [10,20,30,40]
b = [1,3]
a.filter((x,i) => b.includes(i))
// [20, 40]
4
  • @Redu, this would only work for sequential chunks Commented Apr 30, 2017 at 16:38
  • Sorry, my code had a mistake. I've updated the question Commented Apr 30, 2017 at 16:39
  • 4
    You have changed the question so now you have to do b.map(i => a[i]) assuming b always carries indices mapping on some item in a Commented Apr 30, 2017 at 16:41
  • @Redu got it. Yes, that's better than what I was doing. I thought there might be something like a.select(b) Commented Apr 30, 2017 at 16:44

3 Answers 3

12

Another way would be b.map(aIndex => a[aIndex]). If b is shorter than a this could also be faster. However if there are indexes in b that do not belong in a, you would end up with undefined "holes" in the array.

EDIT

Looking a bit into Array.includes, looks like it will run in O(n) for unsorted arrays. If we say A = a.length and B = b.length, your solution from the question should run in O(A * B). The second solution (with map) will run in O(B). To fix the undefined holes, you could add a .filter(element => typeof element !== 'undefined'). The final solution would then be b.map(i => a[i]).filter(e => typeof e !== 'undefined'). This now runs in O(2 * B), which should still be better than O(A * B).

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

Comments

3

I think your solution is just great. map is a great solution too.

For the record, you could use a for...of loop, but it becomes much more complex for nothing...

let a = [10, 20, 30, 40],
    b = [1, 3];

let res = [];
for (const entry of a.entries()) {
  if (b.includes(entry[0])) {
    res.push(entry[1]);
  }
}

console.log(res);

Comments

2

This (and more) can be done with Lodash's at function:

_.at([10, 20, 30, 40], [1, 3]) // [20, 40]
_.at(['a', 'b'], [0, 1, 1, 0]) // ['a', 'b', 'b', 'a']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.