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

find array value that index matches another array values

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

I have the following 2 arrays

tokenIds = [0,1,3]

and

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

what would be the best way to create a new array with the elements in "strings" array which index's match the values of "tokenIds" array?

Such as creating a new array like the following

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

I have tried the following:

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

Thanks in advance!

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

Just map the tokenIds array:

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