首页 > 解决方案 > 如何根据另一个数组中的值获取数组中值的索引?

问题描述

好的,所以有两个数组。另一个是二维的,如下所示:

const locations = [
['London', 60.205490, 24.655899],
['Rome', 60.294411, 25.040070],
['Berlin', 60.262800, 24.824730],
['New York', 60.1698557, 24.9383791],
['Paris', 60.629951, 24.858080],]

const cities = ['London', 'Paris', 'Berlin' ]

我如何比较两个数组以获得这样的结果:

const indexArr = [0, 4, 2]

标签: javascriptjqueryarrays

解决方案


我认为您正在尝试获得以下结果:

const locations = [
['London', 60.205490, 24.655899],
['Rome', 60.294411, 25.040070],
['Berlin', 60.262800, 24.824730],
['New York', 60.1698557, 24.9383791],
['Paris', 60.629951, 24.858080],]

const cities = ['London', 'Paris', 'Berlin' ]

let temp = [];

cities.forEach(function(someItem, someIndex){
  locations.forEach(function(item, index){
    if(item.indexOf(someItem) >= 0) {
      temp.push(index);
    }
  })
})

console.log(temp);


推荐阅读