Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete array elements by certain criteria

Tags:

arrays

ruby

What's the best and way to do this: I have two arrays:

a=[['a','one'],['b','two'],['c','three'],['d','four']]

and b=['two','three']

I want to delete nested arrays inside a that include elements in b,to get this:

[['a','one']['d','four']

Thanks.

like image 677
m.silenus Avatar asked Feb 02 '11 08:02

m.silenus


People also ask

How do you delete certain items from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do you remove an element from an array based on condition?

To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.

How do I remove multiple elements from an array?

Approach 1: Store the index of array elements into another array which need to be removed. Start a loop and run it to the number of elements in the array. Use splice() method to remove the element at a particular index.

How do you remove an element from an array based on value?

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.


2 Answers

a = [['a','one'],['b','two'],['c','three'],['d','four']]
b = ['two','three']

a.delete_if { |x| b.include?(x.last) }

p a
# => [["a", "one"], ["d", "four"]]
like image 146
Simone Carletti Avatar answered Oct 03 '22 11:10

Simone Carletti


rassoc to the rescue!

 b.each {|el| a.delete(a.rassoc(el)) }
like image 38
steenslag Avatar answered Oct 03 '22 11:10

steenslag