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

1
  • 2
    Show your attempt, please. Commented Feb 25, 2019 at 5:35

2 Answers 2

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) }}
Sign up to request clarification or add additional context in comments.

Comments

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)

5 Comments

Result is = [["1_3", "1_4"], ["2_1", "2_2", "2_3"], ["3_1", "3_2", "3_3"]] but not remove "2_3" and 3_2 on your result
Thanks for trying @RajeshKumar but when i Remove let bypassArr = ["1_2","2_1","2_3","3_2"] like then result is wrong.
I performed the action only if both array counts are same
ok but my count is different.
What problem you have with Martin R's answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.