You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数组的数组的哈希中筛选含G18数组的哈希并返回数据

筛选包含特定数组元素的哈希条目

Got it, let's break this down for you. First, let's clarify the data structure you're working with—sounds like you have a hash where each value is an array of arrays, and you want to pull out only the hash entries where those nested arrays include "G18", right? Let's use concrete examples in two common languages to show how to do this.

Example 1: Ruby

First, let's simulate your data structure:

# Sample hash where values are arrays of arrays
data = {
  inventory_1: [["A12", "B34"], ["C56", "D78"]],
  inventory_2: [["X90", "Y11"], ["G18", "Z23"]],
  inventory_3: [["M45", "N67"]]
}

Step 1: Filter the hash to keep only entries with "G18"

Use select to iterate over the hash, and check if any nested sub-array contains "G18":

# Get the full key-value pairs that match
filtered_hash = data.select do |key, nested_arrays|
  nested_arrays.any? { |sub_array| sub_array.include?("G18") }
end

# Result: {:inventory_2=>[["X90", "Y11"], ["G18", "Z23"]]}

Step 2: Extract only the matching data (values)

If you don't need the hash keys and just want the nested array data:

filtered_data = filtered_hash.values

# Result: [[["X90", "Y11"], ["G18", "Z23"]]]

Example 2: JavaScript

If you're working with JavaScript objects (the equivalent of Ruby hashes), here's how to do it:

First, simulate your data:

// Sample object with nested arrays as values
const data = {
  inventory1: [["A12", "B34"], ["C56", "D78"]],
  inventory2: [["X90", "Y11"], ["G18", "Z23"]],
  inventory3: [["M45", "N67"]]
};

Step 1: Filter matching entries

Use Object.entries() to convert the object to key-value pairs, then filter to keep matches:

// Get matching key-value pairs
const filteredEntries = Object.entries(data).filter(([key, nestedArrays]) => {
  return nestedArrays.some(subArr => subArr.includes("G18"));
});

// Result: [["inventory2", [["X90", "Y11"], ["G18", "Z23"]]]]

Step 2: Extract only the data values

If you just need the nested arrays:

const filteredData = filteredEntries.map(([key, value]) => value);

// Result: [ [["X90", "Y11"], ["G18", "Z23"]] ]

Key Logic Explained

  • Traversal: We iterate over each entry in the hash/object to check its value.
  • Nested Check: We use any? (Ruby) or some (JS) to see if at least one sub-array contains "G18"—this avoids unnecessary checks once we find a match.
  • Extraction: Use values (Ruby) or map (JS) to pull out just the data you need, if you don't want to keep the hash keys.

If your data structure is slightly different (e.g., hash values are single arrays instead of arrays of arrays), just adjust the check to arrays.include?("G18") (Ruby) or arrays.includes("G18") (JS).

内容的提问来源于stack exchange,提问作者Jeremiah S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:14:59