根据包含索引的数组从数组中获取元素

时间:2019-11-09 16:53:59

标签: javascript

我有两个数组:

1- inventory包含一些元素

2- indices_dates,其中包含我要从inventory获取的元素的索引。

是否有一种简单的方法来创建由inventory的元素组成的数组,如果它们的索引包含在indices_dates

示例:

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---

我想要的输出:

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]])
}

但是我想知道是否还有另一种更直接的方法来实现它。

2 个答案:

答案 0 :(得分:6)

您可以使用 @foreach($data as $r) <span>{{ $r->latitude }}</span> @endforeach 来迭代索引数组,并从Array.map()中获取值:

inventory

答案 1 :(得分:1)

您可以按照@Ori的建议进行操作,也可以选择以下解决方法:

另一种方法是使用 forEach

numColumns={3}

使用

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)