Search code examples
iosarraysswiftswift3closures

Swift 3 array - remove multiple elements with help of other array


Swift 3:
I've two arrays, one is an array of the dictionary(json) and another is of indexes (Int value) of index Path (Collection type Index with element row & section). With the help of index rows of the second array, I need to remove, elements from the first array.

var arrayString = [ // Array with Json elements
  { "name" : "A" }, 
  { "name" : "B" }, 
  { "name" : "C" }, 
  { "name" : "D" }, 
  { "name" : "E" }, 
  { "name" : "F" }, 
  { "name" : "G" }, 
  { "name" : "H" } 
]

Now Second array (to be removed from the first array)

var arrayIndex = [ 2, 3, 5 ] // Array with 

How can I do this? I want resulting array like

var arrayString = [ 
       { "name" : "A" }, 
       { "name" : "D" }, 
       { "name" : "F" }, 
       { "name" : "G" }, 
       { "name" : "H" } 
    ]

Solution

  • Your array arrayIndex is look like Array of Int not array of IndexPath.

    arrayIndex.sorted(by: >).forEach { if $0 < self.arrayString.count { self.arrayString.remove(at: $0) } }  
    

    If arrayIndex is Array of IndexPath then use row property to remove the object from array.

    arrayIndex.sorted(by: { $0.row > $1.row }).forEach { if $0.row < self.arrayString.count { self.arrayString.remove(at: $0.row) } }