1

I have a json data like below :

data :[
{
  "application_number": 1274930,
  "status": "Removed",
},
{
  "application_number": 1550670,
  "status": "Registered",
  
},
{
  "application_number": 1562368,
  "status": "Registered",
},
{
  "application_number": 1625492,
  "status": "Objected",
},
{
  "application_number": 1644092,
  "status": "Registered",
},
{
  "application_number": 1691808,
  "status": "Removed",
},
{
  "application_number": 1726161,
  "status": "Registered",
}
]

I want to get the unique values of status only. Something like this:

["Removed", "Objected", "Registered"]

I found a similar question and solution there was in javascript :- _.keys(_.countBy(data, function(data) { return data.name; }));

Is there a similar way in ruby to find this ?

Labani Das
  • 349
  • 3
  • 10
  • 1
    *"The actual json data is very large so this can't be done using a loop."* Not sure what you mean by this but the javascript you provided is a loop. if what is posed is your actual data then the most efficient way would likely be something like `require 'set', s = Set.new; data.each {|h| s.add?(h["status"])}` or `data.group_by {|h| h["status"]}.keys` or `data.uniq {|h| h["status"]}` but all of these are loops. I am not sure how you would possibly solve this without a loop. – engineersmnky Nov 15 '22 at 19:53
  • Your problem sounds very similar to [this one about reading a large file, parsing it line by line, and writing out a result](https://stackoverflow.com/q/39031541/3784008). If you can mutate the JSON so that each element is on a single line then it becomes very easy, otherwise you'll need to read four lines, parse it, extract the value, then move to the next four lines. – anothermh Nov 15 '22 at 21:36

1 Answers1

0

you achieve this by following ways:

uniq_status = []
data.each do |tupple|
  uniq_status << tupple['status'] if status.include?(tupple['status'])
end
uniq_tupple 
#$> ["Removed", "Objected", "Registered"


data.collect{|tupple|tupple["status"]}.uniq
#$> ["Removed", "Objected", "Registered"


data.group_by {|tupple| tupple["status"]}.keys
#$> ["Removed", "Objected", "Registered"


data.uniq {|tupple| tupple["status"]}.collect{|tupple|tupple['status']}
#$> ["Removed", "Objected", "Registered"

I hope this will help you.

Amol Mohite
  • 603
  • 3
  • 10