Remove All Elements Contained in Another Array

Remove all elements contained in another array

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
return !toRemove.includes( el );
} );

Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

Remove object from array if it is contained in another array

Not very optimal, but try this

array = array.filter( function( item ){
return array2.filter( function( item2 ){
return item.Email == item2.Email;
}).length == 0;
});

Try with find as well, it won't iterate all the elements and will break after first match itself

array = array.filter( function( item ){
return array2.find( function( item2 ){
return item.Email == item2.Email;
}) == undefined;
});

Deleting items present in another array from original array in JavaScript?

This is how i achieved this, obviously there are better implementations or simpler ones

function except(array,excluded) {
console.log(array.filter((item) => excluded.indexOf(item) === -1));
}

the function except expects the original array and the values user wants to remove,
according to MDN filter method creates a new array with all elements that pass the test implemented by the provided function.

In our case the provided function is the indexOf(item) , where -1 means if not equal to, so the filter function is filtering values after removing those that are in excluded array.
So the output we see is:

Array(3) [ 4, 2, 3 ]

Remove array of objects from another array of objects

How about this solution? It assumes that 'b' is also an array so for each element of 'a' you check if there is a matching object in 'b'. If there is a matching object then return a false in the filter function so that that element is discarded.

var a = [{  'id': '1',  'name': 'a1'}, {  'id': '2',  'name': 'a2'}, {  'id': '3',  'name': 'a3'}]var b = [{  'id': '2',  'name': 'a2'}]
var c = a.filter(function(objFromA) { return !b.find(function(objFromB) { return objFromA.id === objFromB.id })})
console.log(c)

Removing elements from an array that are in another array

Based on this solution to Find the row indexes of several values in a numpy array, here's a NumPy based solution with less memory footprint and could be beneficial when working with large arrays -

dims = np.maximum(B.max(0),A.max(0))+1
out = A[~np.in1d(np.ravel_multi_index(A.T,dims),np.ravel_multi_index(B.T,dims))]

Sample run -

In [38]: A
Out[38]:
array([[1, 1, 1],
[1, 1, 2],
[1, 1, 3],
[1, 1, 4]])

In [39]: B
Out[39]:
array([[0, 0, 0],
[1, 0, 2],
[1, 0, 3],
[1, 0, 4],
[1, 1, 0],
[1, 1, 1],
[1, 1, 4]])

In [40]: out
Out[40]:
array([[1, 1, 2],
[1, 1, 3]])

Runtime test on large arrays -

In [107]: def in1d_approach(A,B):
...: dims = np.maximum(B.max(0),A.max(0))+1
...: return A[~np.in1d(np.ravel_multi_index(A.T,dims),\
...: np.ravel_multi_index(B.T,dims))]
...:

In [108]: # Setup arrays with B as large array and A contains some of B's rows
...: B = np.random.randint(0,9,(1000,3))
...: A = np.random.randint(0,9,(100,3))
...: A_idx = np.random.choice(np.arange(A.shape[0]),size=10,replace=0)
...: B_idx = np.random.choice(np.arange(B.shape[0]),size=10,replace=0)
...: A[A_idx] = B[B_idx]
...:

Timings with broadcasting based solutions -

In [109]: %timeit A[np.all(np.any((A-B[:, None]), axis=2), axis=0)]
100 loops, best of 3: 4.64 ms per loop # @Kasramvd's soln

In [110]: %timeit A[~((A[:,None,:] == B).all(-1)).any(1)]
100 loops, best of 3: 3.66 ms per loop

Timing with less memory footprint based solution -

In [111]: %timeit in1d_approach(A,B)
1000 loops, best of 3: 231 µs per loop

Further performance boost

in1d_approach reduces each row by considering each row as an indexing tuple. We can do the same a bit more efficiently by introducing matrix-multiplication with np.dot, like so -

def in1d_dot_approach(A,B):
cumdims = (np.maximum(A.max(),B.max())+1)**np.arange(B.shape[1])
return A[~np.in1d(A.dot(cumdims),B.dot(cumdims))]

Let's test it against the previous on much larger arrays -

In [251]: # Setup arrays with B as large array and A contains some of B's rows
...: B = np.random.randint(0,9,(10000,3))
...: A = np.random.randint(0,9,(1000,3))
...: A_idx = np.random.choice(np.arange(A.shape[0]),size=10,replace=0)
...: B_idx = np.random.choice(np.arange(B.shape[0]),size=10,replace=0)
...: A[A_idx] = B[B_idx]
...:

In [252]: %timeit in1d_approach(A,B)
1000 loops, best of 3: 1.28 ms per loop

In [253]: %timeit in1d_dot_approach(A, B)
1000 loops, best of 3: 1.2 ms per loop

Removing elements that in another array

I'm guessing the issue has to do with how you are looping and removing items in the list, making the program skip over the third 10.

You can use a quick list comprehension to solve the issue:

array3 = [i for i in array2 if i not in array1]

This is basically a simpler way of typing:

array3 = []
for i in array2:
if i not in array1:
array3.append(i)

Additionally, you probably wouldn't want to use sets. For example:

array1 = [1, 2, 3]
array2 = [1, 2, 3, 3, 4, 4, 5, 6]

array3 = list(set(array2) - set(array1))

array3 will only contain [4, 5, 6], rather than [4, 4, 5, 6], since sets cannot contain duplicates.

Remove array elements that are present in another array

You can use .reject to exclude all banned words that are present in the redacted array:

words.reject {|w| redacted.include? w}

Demo

If you want to get the list of banned words that are present in the words array, you can use .select:

words.select {|w| redacted.include? w}

Demo

How can I remove object in one array from another array?

Use the method RemoveAll, here the doc

Example:

public static void main(String[] args) {
List<Integer> numbersA = new ArrayList<>();
List<Integer> numbersB = new ArrayList<>();
numbersA.addAll(Arrays.asList(new Integer[] { 1, 3, 4, 7, 5, 2 }));
numbersB.addAll(Arrays.asList(new Integer[] { 13, 32, 533, 3, 4, 2 }));
System.out.println("A: " + numbersA);
System.out.println("B: " + numbersB);

numbersB.removeAll(numbersA);
System.out.println("B cleared: " + numbersB);
}

this will print

A: [1, 3, 4, 7, 5, 2]

B: [13, 32, 533, 3, 4, 2]

B cleared: [13, 32, 533]

Remove values in 1d array contained in another array

With duplicates

In general, removing while iterating is not a good idea, since you can easily skip values. One way you can do this is defining a boolean mask from the result of np.isin and use it to index q_active. Using this method you'd keep all instances of duplicate values:

select_act = np.array([2])
q_active = np.array([2, 3, 4, 2, 3])

m = np.isin(q_active, select_act, invert=True)
# array([ True, False])
q_active[m]
# array([3, 4, 3])

Without duplicates

It might also be worth mentioning np.setdiff1d, which in the case there are no duplciates and order is not important is good option:

select_act = np.array([2])
q_active = np.array([4, 2, 3])

np.setdiff1d(q_active, select_act)
# array([3, 4])

Comparison between both methods (interesting in the case we don't want to keep duplicates, otherwise the former is needed):

q_active = np.random.randint(1,20_000,10_000)
select_act = np.random.randint(1,20_000,5_000)

%%timeit
m = np.isin(q_active, select_act, invert=True)
q_active[m]
# 1.01 ms ± 14.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
m = np.in1d(q_active, select_act, invert=True)
q_active[m]
# 1.01 ms ± 26.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit np.setdiff1d(q_active, select_act)
# 808 µs ± 7.54 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


Related Topics



Leave a reply



Submit