0

I have a json array that i get back from an api (sample below) . say I want to sort the data based on age, and also select first 5 of them, how can I do this in ruby?

[  
    {"name":"Richard", "email":"[email protected]", "age" : "32"},  
    {"name":"Bob", "email":"[email protected]", "age" : "52"}, 
    ....
]  

1 Answer 1

2

Let's say your array

arr=[

    {"name"=>"Richard", "email"=>"[email protected]", "age" => "32"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "52"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "21"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "58"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "45"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "67"},
    {"name"=>"Bob", "email"=>"[email protected]", "age" => "92"}
]

Code

p arr.sort_by{|h|h['age']}.first(5)
#=>[{"name"=>"Bob", "email"=>"[email protected]", "age"=>"21"}, {"name"=>"Richard", "email"=>"[email protected]", "age"=>"32"}, {"name"=>"Bob", "email"=>"[email protected]", "age"=>"45"}, {"name"=>"Bob", "email"=>"[email protected]", "age"=>"52"}, {"name"=>"Bob", "email"=>"[email protected]", "age"=>"58"}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.