[英]use array of indexes to filter another array javascript
我有 1 个数组和 1 个集合,集合Indexes
和数组是Names
。
Indexes 包含各种数字,这些数字基本上是Names
数组的随机元素的索引。我想根据 Indexes 数组中的索引过滤 Names 数组,即将 Names 数组的特定元素推送到索引存在于 Indexes 数组中的另一个数组。
我正在做的是:
const Indexes =[0,1]
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = Indexes.map(item => Names[item]);
Output 应该是:
filteredNames=["Test1","Test2"]
但它不起作用。有什么线索吗?
它也适用于 set
const Indexes =new Set([0,2]); let temp=Array.from(Indexes); const Names=["Test1","Test2","Test3","Test4"] const filteredNames = temp.map(item => Names[item]); console.log(filteredNames)
你几乎猜对了
const Indexes =[0,1] const Names=["Test1","Test2","Test3","Test4"] const filteredNames = Indexes.map(item => Names[item]); console.log(filteredNames)
如果索引是一个集合,那么你只需要Array.from
函数:
const Indexes =new Set([0,1])
const Names=["Test1","Test2","Test3","Test4"]
const filteredNames = Array.from(Indexes)
.map(item => Names[item]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.