Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter to exclude elements from array

Tags:

Trying to filter some entries from an array. It's not guaranteed they are in the master array, so I'm testing through an iteration.

total = ['alpha', 'bravo', 'charlie', 'delta', 'echo'] hide = ['charlie', 'echo']  pick = [] for i in total   if !hide.include?(i)     puts i     pick.push(i)   end end puts pick 

This isn't working. Is there a better way of providing this kind of filter?

like image 259
Rich_F Avatar asked Sep 07 '15 10:09

Rich_F


People also ask

How do you exclude an element from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.

How do you remove an element from an array array?

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.

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.


1 Answers

Ruby lets you use public instance methods on two arrays to get their intersecting or exclusive elements:

a1 = ['alpha', 'bravo', 'charlie', 'delta', 'echo'] a2  = ['charlie', 'echo'] puts a1 - a2 =>  ['alpha', 'bravo', 'delta']  puts a1 & a2 =>  ['charlie', 'echo'] 

For more information check rubydoc Array. It's likely that you'll find exactly what you need there.

like image 112
The F Avatar answered Sep 22 '22 06:09

The F