简体   繁体   中英

Conditional removal of elements from an array

I am trying to construct some JSON data using my newly acquired but incomplete ruby knowledge. It basically is part of a rails application where the database is 1 user to many relationships (fields follower_id and followed_id). The format of the JSON should be:

{"nodes":["1","102","10","61","6","54","29","84","82"],"edges":[["1","54"],["10","29"],["61","84"],["1","61"],["10","82"]]}

I would like to remove any edge arrays where both or one of the numbers are not present in the nodes array. The real files are likely to be much larger than this so the most efficient way possible to do this would be great.

My code is as follows:

def self.joinup(id)
  c = Challenge.find(1)
  result={}
  user_ids  =  c.users.pluck(:id)
  result["nodes"] = user_ids.collect(&:to_s).flatten.uniq
  result["edges"] = Relationship.where(follower_id: user_ids).map{|h| [h.follower_id.to_s, h.followed_id.to_s]}

  #if elements of edges are not present in nodes then remove doublet
  result["nodes"] = result["nodes"]|result["edges"].flatten
  result
 end
 end

What I understand is you want to remove dangling relationships ( edges ) where both or one of which are no longer in the users table( nodes array ).

Then this should do it:

result["edges"].select! {|edge| result["nodes"].include?(edge[0]) && result["nodes"].include?(edge[1]) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM