繁体   English   中英

使用索引数组过滤另一个数组 javascript

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM