如何快速从2D数组中删除特定元素

时间:2019-02-25 05:31:45

标签: arrays swift filter

我有一个[[String]]喜欢

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

我要删除这样的元素 bypassArr = ["1_2","2_3","3_2"]

如何使用element从bypassArr中删除myArr。或如何获得这种结果。

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

如果打算从bypassArr除去“内部”数组中myArr的所有元素,那么map()filter()的组合将达到目的:

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"]]

对内部数组进行过滤,以删除给定的元素,对外部数组进行映射,以过滤结果。

或使用简写参数表示法:

let result = myArr.map { $0.filter { !bypassArr.contains($0) }}