Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing objects from an array based on another array

I have two arrays like this:

var arrayA = ["Mike", "James", "Stacey", "Steve"] var arrayB = ["Steve", "Gemma", "James", "Lucy"] 

As you can see, James and Steve match and I want to be able to remove them from arrayA. How would I write this?

like image 495
Henry Brown Avatar asked Apr 13 '15 18:04

Henry Brown


People also ask

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.

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.


2 Answers

@francesco-vadicamo's answer in Swift 2/3/4+

 arrayA = arrayA.filter { !arrayB.contains($0) } 
like image 196
Federico Zanetello Avatar answered Oct 14 '22 12:10

Federico Zanetello


The easiest way is by using the new Set container (added in Swift 1.2 / Xcode 6.3):

var setA = Set(arrayA) var setB = Set(arrayB)  // Return a set with all values contained in both A and B let intersection = setA.intersect(setB)   // Return a set with all values in A which are not contained in B let diff = setA.subtract(setB) 

If you want to reassign the resulting set to arrayA, simply create a new instance using the copy constructor and assign it to arrayA:

arrayA = Array(intersection) 

The downside is that you have to create 2 new data sets. Note that intersect doesn't mutate the instance it is invoked in, it just returns a new set.

There are similar methods to add, subtract, etc., you can take a look at them

like image 20
Antonio Avatar answered Oct 14 '22 12:10

Antonio