Home > OS >  swift filter 2d array by some value
swift filter 2d array by some value

Time:12-07

I have an array like this

var cinema = Array(repeating: Array(repeating: 0, count: 30), count: 5)

user might input some values like this

cinema[1][20] = 5
cinema[1][21] = 6

Now, I would like to find out all nun 0 values and its index. I think it is maybe possible to do it by for loop, but this is takes more time. Is there a way to use something simpler? such as array.filter?

CodePudding user response:

cinema.map {
  $0.enumerated().filter { $0.element != 0 }
}

CodePudding user response:

The code from @Jessy is correct.

cinema.map {
  $0.enumerated().filter { $0.element != 0 }
}

Additionally, one could try follows as well:

for (i, row) in cinema.enumerated() {
    for (j, cell) in row.enumerated().filter({$0.element != 0 }) {
      print("m[\(i),\(j)] = \(cell)")
  }
}
  • Related