• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Ruby – Sort a hash by order of an array

Resolved: Ruby – Sort a hash by order of an array

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have an array and a hash and what I want to achieve is to sort the hash (with each id inside each hash) based on the sort that is in the array and if the id (in hash) doesn’t exist in my_array, they should not be deleted and just be pushed down in the sort.
Needed output
Appreciate any help and thanks in advance!

Answer:

Note that I’ve changed my_array from that given in the question and have renamed the array to something more appropriate.
See Enumerable#sort_by. That method uses Array#<=> to order elements. See especially the third paragraph at the doc for <=>.
Below I’ve listed the arrays used by sort_by for each element of arr.
If [type, x] is the array sort_by uses for sorting, it will put all elements for which type 0 before those for which type = 1. To break ties it orders elements by x. For type = 1, x is the index of the element, which keeps them in order at the end.

If you have better answer, please add a comment about this, thank you!

arrays hash ruby sorting
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Modify entity using Action in C#

24/03/2023

Resolved: How to give rank on datetime column group by another column with userid in it

24/03/2023

Resolved: Passing 2 functions in onChange in react

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.