Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to an array if it's not there already

Tags:

ruby

I have a Ruby class

class MyClass   attr_writer :item1, :item2 end  my_array = get_array_of_my_class() #my_array is an array of MyClass unique_array_of_item1 = [] 

I want to push MyClass#item1 to unique_array_of_item1, but only if unique_array_of_item1 doesn't contain that item1 yet. There is a simple solution I know: just iterate through my_array and check if unique_array_of_item1 already contains the current item1 or not.

Is there any more efficient solution?

like image 807
Alan Coromano Avatar asked Dec 22 '12 16:12

Alan Coromano


People also ask

How do you add an object to an existing array?

The unshift() method is used to add one or multiple elements to the beginning of an array. It returns the length of the new array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the beginning of the array.

How do you add elements to an array without overwriting the first one?

Another way to add/insert an element into an array is to use the . splice() method. With . splice() you can insert a new element at any given index, either overwriting what is currently in that index number, or inserting within, with no overwriting.

How do you add an element to an array array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

How do you check if an element is already in an array?

The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.


2 Answers

@Coorasse has a good answer, though it should be:

my_array | [item] 

And to update my_array in place:

my_array |= [item] 
like image 105
Jason Denney Avatar answered Oct 07 '22 15:10

Jason Denney


You can use Set instead of Array.

like image 36
Jiří Pospíšil Avatar answered Oct 07 '22 16:10

Jiří Pospíšil