热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

按idRUBY数组排序-SortbyarrayofidsRUBY

sort_by_this_array[4,2,1,3]<--Thisisarrayofattributegoal_id.sort_by_this_array[4,2,1

sort_by_this_array = [4,2,1,3] <-- This is array of attribute goal_id.

sort_by_this_array =[4,2,1,3] <——这是属性目标的数组。

& then I have my

然后是我的。

[, , , , , , ] 

Result should be: id: 40, 12,13,7, 6,30, 25

结果应该是:id: 40、12、13、7、6、30、25

I'm thinking about 2 loops & it's definitely not the best way.

我在考虑两个循环,这绝对不是最好的方法。

3 个解决方案

#1


5  

Maybe try this approach:

也许试试这种方法:

S = Struct.new(:id, :v)
a = Array.new(5) { |i| S.new(i, i) }
a.shuffle!
a.sort_by {|e| [2, 3 , 1 , 4, 0].index(e.id) }

It will return your a in order by ids.

它将按id顺序返回a。

#2


1  

You may want to use variation of sorting by selection where swapping would occur each time you find a 'todo' element for which its 'goal_id' attribute is equal to 'goal_id' from your array.

您可能希望通过选择使用排序的变化,在每次找到一个'todo'元素时,在这个元素的'goal_id'属性等于数组中的'goal_id'。

Todo = Struct.new(:id, :goal_id)
todos = [Todo.new(12,2), Todo.new(13,2),Todo.new(6,1), Todo.new(7,2), Todo.new(25,3), Todo.new(30,1), Todo.new(40,4)]
sort_by_this_array = [4,2,1,3]

j = 0
sort_by_this_array.each do |goal_id|
  todos.each_with_index do |todo,i|
    if todo.goal_id == goal_id
      todos[i],todos[j] = todos[j],todos[i]
      j += 1
    end
  end
end

I would reccommend reading some sources on the web about sorting by selection. As this is a simple variation of it http://www.sorting-algorithms.com/selection-sort

我会推荐在网上阅读一些关于选择排序的资料。因为这是它的一个简单变体http://www.sorting-algorithms.com/selection-sort

Unfortunately this solution will not preserve order of elements inside initial todos array, as each swapping changes the position on which todo element is located. So they will be sorted, but it will be not stable.

不幸的是,这个解决方案不会保留初始todos数组中元素的顺序,因为每次交换都会改变todo元素所在的位置。所以它们是有序的,但是不稳定。

Below stable solution with additional memory.

下面是稳定的解决方案和额外的内存。

j = 0
results = []
sort_by_this_array.each do |goal_id|
  while idx = todos.index {|e| e.goal_id == goal_id}
    results <

#3


0  

You can try this:

你可以试试这个:

Todo.all.sort_by{|e| e[:goal_id]}

Check this post

检查这篇文章


推荐阅读
author-avatar
bj韩式尕伙
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有