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

如何使用Ruby按对象属性对数组进行交替均匀排序

Ruby实现数组按store属性交替排序

实现思路

  • 先将原数组按store属性值分组,保留各组内元素的原有先后顺序
  • 按A→B的循环顺序交替从分组中取元素,直到所有元素提取完成

最简实现(适用于仅A、B两个store值的场景)

# 原数组
arr = [
   { name: 'Apple', store: 'A' },
   { name: 'Banana', store: 'A' },
   { name: 'Carrot', store: 'B' },
   { name: 'Potato', store: 'B' },
   { name: 'Tomato', store: 'A' }
]

# 分组提取对应store的元素列表
grouped = arr.group_by { |item| item[:store] }
a_list = grouped['A'] || []
b_list = grouped['B'] || []

# 交替拼接数组
sorted_arr = a_list.zip(b_list).flatten.compact

执行后sorted_arr的输出为:

[
  {:name=>"Apple", :store=>"A"},
  {:name=>"Carrot", :store=>"B"},
  {:name=>"Banana", :store=>"A"},
  {:name=>"Potato", :store=>"B"},
  {:name=>"Tomato", :store=>"A"}
]

注:你给出的预期结果存在笔误,原数组中Tomato的store属性为A,预期结果里误写为B,上述输出为符合逻辑的正确结果。

通用实现(适配任意长度、多store循环场景)

如果需要支持严格按A→B的循环逻辑取元素,或者后续扩展更多store类型,可以用下面的实现:

grouped = arr.group_by { |item| item[:store] }.transform_values(&:dup)
sorted_arr = []
current_expected = 'A'

until grouped.values.all?(&:empty?)
  if grouped[current_expected]&.any?
    sorted_arr << grouped[current_expected].shift
  end
  # 切换下一个期望的store值
  current_expected = current_expected == 'A' ? 'B' : 'A'
end

内容的提问来源于stack exchange,提问作者jujajjjj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:45:00