【问题标题】:Finding Matching Templates and Getting Value Corresponding to It In Array查找匹配的模板并在数组中获取与其对应的值
【发布时间】:2021-08-24 23:20:10
【问题描述】:

我已经研究过使用过滤器、包含、一些和其他解决方案,但似乎没有什么适合这个。

这是我的数据出现的方式——我需要得到一个只包含的数组:

  1. 每辆车的模板 ID
  2. 车辆的数量([3] 位置值)

感谢您的任何建议!

var vehicleTemplates = [
  ["230478", "uncommon", "Yellow Starship X2", "6"],
  ["230477", "uncommon", "Blue Starship X2", "6"],
  ["230476", "uncommon", "Green Starship X2", "6"],
  ["230473", "uncommon", "Red Starship X2", "6"],
  ["218034", "uncommon", "Purple Hovercraft W1", "4"],
  ["218033", "uncommon", "Yellow Hovercraft W1", "4"],
  ["218032", "uncommon", "Blue Hovercraft W1", "4"],
  ["218031", "uncommon", "Green Hovercraft W1", "4"],
  ["218029", "uncommon", "Red Hovercraft W1", "4"],
  ["218022", "uncommon", "Purple Truck T2", "6"],
  ["218021", "uncommon", "Yellow Truck T2", "6"],
  ["218019", "uncommon", "Blue Truck T2", "6"],
  ["218018", "uncommon", "Green Truck T2", "6"],
  ["218017", "uncommon", "Red Truck T2", "6"],
  ["208508", "common", "Standard Starship X2", "6"],
  ["208507", "common", "Standard Hovercraft W1", "4"],
  ["208506", "common", "Standard Truck T2", "6"]
];

var playerInventory = [
  ["115794", "uncommon", "Non Vehicle", "6"],
  ["230473", "uncommon", "Red Starship X2", "6"], 
  ["218034", "uncommon", "Purple Hovercraft W1", "4"],
  ["218033", "uncommon", "Yellow Hovercraft W1", "4"], 
  ["218022", "uncommon", "Non Vehicle", "4"]
];

我需要得到一个数组,该数组只包含玩家在playerInventory中拥有的车辆ID

然后我想获取数组中的第三项——该车辆 id 的车辆数量。

【问题讨论】:

  • 请将想要的结果添加为数据和您的尝试。

标签: javascript arrays filtering


【解决方案1】:

直截了当的回答

const multiArr = [
        ["21212", "uncommnon", "orange"],
        ["65565", "common", "blue"],
        ["87878", "uncommnon", "yellow"]
    ]

 const idArray = multiArr.map(ids => ids[0])

更好的解决方案

使用字典

这种数据结构可能看起来很直观,但它会导致在处理这种数据结构时做出混乱的决策。

如果 id 不是第一个元素怎么办? (例如)

这是一种硬编码且不可扩展的数据选择。

这是更好的选择

const dictionary = {
        "23232" : { rarity: "uncommon", color: "blue" },
        "65565" : { rarity: "common", color: "yellow" },
        "87878" : { rarity: "uncommon", color: "pink" }
}

dictionary["23232"]

您使用 ids 进行搜索、插入、删除操作将是 o(1),您可以更好地访问数据并轻松获得一组键 (ids)

Object.keys(dictionary)

【讨论】:

    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多