-1

How can I remove values array based on array other.

Example :-

Type ( Int )

var arrayOne = [1,2,3,4,5,6,7,8]

var arrayTwo = [1,2,4,5,6,7]


I want the next result :-

result = [3,8]

Community
  • 1
  • 1
  • Check this [Possible duplicate](https://stackoverflow.com/a/29852086/3589771). Browser before asking a question in StackOverflow. StackOverflow also has an option for documentation. In your case check this [documentation for `set`](https://stackoverflow.com/documentation/swift/371/sets/1632/performing-operations-on-sets#t=201707120506132185625) – Mathi Arasan Jul 12 '17 at 05:05
  • There is much resources to read about array manipulation with a simple google search. read https://stackoverflow.com/questions/35680135/filter-two-arrays-swift#comment59040041_35680166 – Gihan Jul 12 '17 at 05:21

4 Answers4

1

User Set for simple result

var arrayOne = [1,2,3,4,5,6,7,8]

var arrayTwo = [1,2,4,5,6,7]

let set1:Set<Int> = Set(arrayOne)
let set2:Set<Int> = Set(arrayTwo)

let set3 =  set1.symmetricDifference(set2)

Output :

{3, 8}

Jaydeep Vyas
  • 4,411
  • 1
  • 18
  • 44
0

You can do it by converting them to Sets.

var arrayOne = [1,2,3,4,5,6,7,8]
var arrayTwo = [1,2,4,5,6,7]

let set1:Set<String> = Set(arrayOne)
let set2:Set<String> = Set(arrayTwo)

Use ExclusiveOr to do this.

    //Swift 2.0
    set1.exclusiveOr(array2) // result = {3,8}

   //Swift 3.0
   set1.symmetricDifference(set2) // result = {3,8}

This link might useful for you: Set operations (union, intersection) on Swift array? also possible Duplicate as @user3589771 said.

Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
0

Use following working code -

let arrayOne = [1,2,3,4,5,6,7,8]
let arrayTwo = [1,2,4,5,6,7]
var result = [Int]()

for value in arrayOne
{
     if !arrayTwo.contains(value)
     {
         result.append(value)
     }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nilesh
  • 533
  • 7
  • 19
0

You can do with below options.

// Option 1 - Using Set's

let arrayOne : Set = [1,2,3,4,5,6,7,8]

let arrayTwo : Set = [1,2,4,5,6,7]

var result = arrayOne.symmetricDifference(arrayTwo)

print(result) // {3,8}

// Option 2 - Using Array

var result1 = [Int]()

for value in arrayOne
{
    if !arrayTwo.contains(value)
    {
        result1.append(value)
        }
    }

print(result1) // {3,8}
Bhavesh Dhaduk
  • 1,888
  • 15
  • 30