1

I have an nested array and want to remove the entries that matches the info on my model.

My array looks roughly like this:

[{"id"=>"72157627540544488", "primary"=>"6090588224", "photos"=>"49", "videos"=>0, "title"=>"Title1", "description"=>""},
{"id"=>"72157627309708150", "primary"=>"5987891163", "photos"=>"49", "videos"=>0, "title"=>"Title2", "description"=>""},
{"id"=>"72157626646787712", "primary"=>"5687687064", "photos"=>"11", "videos"=>0, "title"=>"Title3", "description"=>""},
{"id"=>"72157626646672290", "primary"=>"5687629990", "photos"=>"33", "videos"=>0, "title"=>"Title4", "description"=>""}] 

And my model:

id               :integer         not null, primary key
name             :string(255)
set_id           :integer
thumb_url        :string(255)
created_at       :datetime
updated_at       :datetime

What I'm trying to accomplish is to remove from the array all the elements where the value of id is duplicated in any of the set_id in my model.

1 Answer 1

1

You can do something like:

array.reject{|element| Model.exists?(:set_id => element['id'])}

where array is the array and Model is the model class. This will return a new array with the elements with duplicate id's removed.

Array.reject returns a copy of the array without the elements where the block passed in returns true.

ActiveRecord.exists? returns true if a model exists in the database with the given conditions.

Sign up to request clarification or add additional context in comments.

3 Comments

It worked! Just wondering if there's a way to do the same but using another array instead of a Model. Would include? do the trick?
I tried to do the same but using a instance variable instead of the Model to avoid another query to the database. I came up with this: 'array.reject{|element| @variable.any?{|item| item.set_id == element['id']}}'
Yep, that works. I can't really think of a more concise way to do that with an array.

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.