Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete one element from an array by value

Tags:

arrays

ruby

I have an array of elements in Ruby

[2,4,6,3,8] 

I need to remove elements with value 3 for example

How do I do that?

like image 767
Tamik Soziev Avatar asked Apr 05 '12 19:04

Tamik Soziev


People also ask

How do you remove an element from an array with value?

You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove a specific value from an array in Java?

To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array.

How do I remove a specific element from an array in Python?

You can use the pop() method to remove an element from the array.


2 Answers

I think I've figured it out:

a = [3, 2, 4, 6, 3, 8] a.delete(3) #=> 3 a #=> [2, 4, 6, 8] 
like image 61
Tamik Soziev Avatar answered Oct 01 '22 20:10

Tamik Soziev


Borrowing from Travis in the comments, this is a better answer:

I personally like [1, 2, 7, 4, 5] - [7] which results in => [1, 2, 4, 5] from irb

I modified his answer seeing that 3 was the third element in his example array. This could lead to some confusion for those who don't realize that 3 is in position 2 in the array.

like image 45
Abram Avatar answered Oct 01 '22 20:10

Abram