How can I delete the first element by a value in an array?
arr = [ 1, 1, 2, 2, 3, 3, 4, 5 ]
#something like:
arr.delete_first(3)
#I would like a result like => [ 1, 1, 2, 2, 3, 4, 5]
Thanks in advance
Ruby | Array delete() operation Array#delete() : delete() is a Array class method which returns the array after deleting the mentioned elements. It can also delete a particular element in the array. Syntax: Array. delete() Parameter: obj - specific element to delete Return: last deleted values from the array.
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated 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.
You can use Array. delete_at(0) method which will delete first element.
Pass the result of Array#find_index
into Array#delete_at
:
>> arr.delete_at(arr.find_index(3))
>> arr
=> [1, 1, 2, 2, 3, 4, 5]
find_index()
will return the Array index of the first element that matches its argument. delete_at()
deletes the element from an Array at the specified index.
To prevent delete_at()
raising a TypeError
if the index isn't found, you may use a &&
construct to assign the result of find_index()
to a variable and use that variable in delete_at()
if it isn't nil
. The right side of &&
won't execute at all if the left side is false
or nil
.
>> (i = arr.find_index(3)) && arr.delete_at(i)
=> 3
>> (i = arr.find_index(6)) && arr.delete_at(i)
=> nil
>> arr
=> [1, 1, 2, 2, 3, 4, 5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With