最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to select elements from an array based on the indices of another array in JavaScript? - Stack Overflow

programmeradmin3浏览0评论

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]

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]
Share Improve this question edited Apr 30, 2017 at 16:38 nachocab asked Apr 30, 2017 at 16:35 nachocabnachocab 14.4k21 gold badges104 silver badges158 bronze badges 4
  • @Redu, this would only work for sequential chunks – Sasang Commented Apr 30, 2017 at 16:38
  • Sorry, my code had a mistake. I've updated the question – nachocab 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 – Redu 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) – nachocab Commented Apr 30, 2017 at 16:44
Add a comment  | 

3 Answers 3

Reset to default 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).

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);

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']
发布评论

评论列表(0)

  1. 暂无评论