![](/img/trans.png)
[英]How to select elements from an array based on the indices of another array in JavaScript?
[英]Get elements from an array based on array containing indices
我有两个 arrays:
1- 包含一些元素的inventory
2- indices_dates
包含我想要从inventory
中获取的元素的索引。
如果它们的索引包含在indices_dates
中,是否有一种简单的方法来创建由inventory
元素形成的数组
例子:
let inventory
let indices_dates
let final = []
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
---Some Code To Get Final Array---
output 我想:
final = [25, 40, 20, 17]
我做了以下事情:
let inventory
let indices_dates
let final = []
let i
inventory = [25, 35, 40, 20, 15, 17]
indices_dates = [0, 2, 3, 5]
for (i in indices_dates) {
final.push(inventory[indices_dates[i]])
}
但我想知道是否有另一种更直接的方法来实现它。
您可以使用Array.map()
迭代索引数组,并从inventory
获取值:
const inventory = [25, 35, 40, 20, 15, 17] const indices_dates = [0, 2, 3, 5] const final = indices_dates.map(idx => inventory[idx]) console.log(final)
您可以按照@Ori 的建议进行操作,或者替代解决方案是:
另一种方法是使用forEach :
const inventory = [25, 35, 40, 20, 15, 17] const indices_dates = [0, 2, 3, 5]; let final = []; indices_dates.forEach(data => final.push(inventory[data])) console.log(final)
使用for :
const inventory = [25, 35, 40, 20, 15, 17] const indices_dates = [0, 2, 3, 5]; let final = []; for (let dateIndex of indices_dates){ final.push(inventory[dateIndex]) } console.log(final)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.