0

I have a [[String]] like

myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]] then

I Want to remove element like this bypassArr = ["1_2","2_3","3_2"]

how to remove bypassArr from myArr using element. or how can i get this type of result.

result = [["1_3","1_4"], ["2_1","2_2"], ["3_1","3_3"]]

ikbal
  • 1,114
  • 1
  • 11
  • 30

2 Answers2

5

If the intention is to remove all elements from bypassArr in the “inner” arrays from myArr then a combination of map() and filter() does the trick:

let myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]]
let bypassArr = ["1_2","2_3","3_2"]

let result = myArr.map { innerArray in
    innerArray.filter { elem in
        !bypassArr.contains(elem)
    }
}

print(result)
// [["1_3", "1_4"], ["2_1", "2_2"], ["3_1", "3_3"]]

The inner arrays are filtered to remove the given elements, and the outer array is mapped to the filtered results.

Or with short-hand parameter notation:

let result = myArr.map { $0.filter { !bypassArr.contains($0) }}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
2
var myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]]
let bypassArr = ["1_2","2_3","3_2"]
if myArr.count == bypassArr.count {
    myArr = bypassArr.enumerated().map({ (index, str) -> [String] in
        if let strPos = myArr[index].firstIndex(of: str) {
            myArr[index].remove(at: strPos)
        }
        return myArr[index]
    })
}
print(myArr)
RajeshKumar R
  • 15,445
  • 2
  • 38
  • 70