Warm tip: This article is reproduced from serverfault.com, please click

javascript-查找索引与另一个数组值匹配的数组值

(javascript - find array value that index matches another array values)

发布于 2020-11-27 23:45:15

我有以下2个数组

tokenIds = [0,1,3]

strings = ["hello", "foo", "goodbye", "bar"]

用索引匹配“ tokenIds”数组值的“字符串”数组中的元素创建新数组的最佳方法是什么?

如创建一个新的数组,如下所示

newstrings = ["hello", "foo", "bar"]

我尝试了以下方法:

const newstrings = strings.filter(index => tokenIds.includes(tokenIds.index));

提前致谢!

Questioner
Simon Palmer
Viewed
0
Aplet123 2020-11-28 07:46:22

只需maptokenIds数组:

const newstrings = tokenIds.map(i => strings[i]);