Reputation: 71
I would like to compare an Array to an element and extract those data in the another Array Here is an example of data i'm working with:
Array = [{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"},
{:id=>4, :keyword=>"happy", :Date=>"01/02/2016"} ... ]
for example i want the first keyword happy to search the same array ,extract if there's any similar words and put them inside another array here is what i'm looking for an end result:
Results = [{:keyword=>happy, :match =>{
{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"}... }]
Here is the first part of the code :
def relationship(file)
data = open_data(file)
parsed = JSON.parse(data)
keywords = []
i = 0
parsed.each do |word|
keywords << { id: i += 1 , keyword: word['keyword'].downcase, Date: word['Date'] }
end
end
Upvotes: 1
Views: 79
Reputation: 1260
Here's another idea that could help you with your situation using enumerable and index:
array to be search:
array = [
{:id=>3, :keyword=>"happy", :Date=>"01/02/2016"},
{:id=>4, :keyword=>"happy", :Date=>"01/02/2016"},
{:id=>1, :keyword=>"happy", :Date=>"01/02/2015"},
{:id=>2, :keyword=>"sad", :Date=>"01/02/2016"},
{:id=>30, :keyword=>"fine", :Date=>"01/02/2017"},
{:id=>41, :keyword=>"happy", :Date=>"01/02/2018"}
]
method search: store all element matching the term in the array.
def search(term, array)
array = []
array << {keyword: "#{term}", match: []}
arr.select { |element| array.first[:match] << element if element[:keyword].index(term) }
array
end
Testing:
p search('sa', array)
# => [{:keyword=>"sa", :match=>[{:id=>2, :keyword=>"sad", :Date=>"01/02/2016"}, {:id=>21, :keyword=>"sad", :Date=>"01/02/2016"}]}]
hope that will get you goin!
Upvotes: 1
Reputation: 54
def search_keyword(keyword)
hash = [
{:id=>1, :keyword=>"happy", :Date=>"01/02/2015"},
{:id=>2, :keyword=>"sad", :Date=>"01/02/2016"},
{:id=>3, :keyword=>"fine", :Date=>"01/02/2017"},
{:id=>4, :keyword=>"happy", :Date=>"01/02/2018"}
]
keywords = []
hash.each do |key|
if key[:keyword] == keyword
keywords << key
end
end
keywords
#{:keyword=> keyword, :match=> keywords}
end
search_keyword('fine')
#search_keyword('sad')
You could group the match elements by key (:match) then get the result with a single hash lookup.
Upvotes: 1