How to use an optional chaining effect

Hello, i am a beginner, I have a problem, use JS:

const arr = [[1, 2], [3, 4]]
console.log([{y:0, x: 1}, {y:1, x: 2}].filter(({ y, x })=> arr[y]?.[x] ))

I tried to use rescript, but it didn’t have the desired effect

You forgot to handle a possible case here, for example: [| |]

let arr = [[1, 2], [3, 4]]
Js.log( Js.Array2.filter([{y:0, x: 1}, {y:1, x: 2}], ([y, x]) => Some(arr[y][x]) !== None))

What should I do

let arr = [[1, 2], [3, 4]]

[{y: 0, x: 1}, {y: 1, x: 2}]
->Js.Array2.filter(({y, x}) =>
  switch arr->Belt.Array.get(y) {
  | Some(arrY) => arrY->Belt.Array.get(x)->Belt.Option.isSome
  | None => false
  }
)
->Js.log

You can also open Belt to implicitly use Belt.Array.get with the array access syntax:

let arr = [[1, 2], [3, 4]]

[{y: 0, x: 1}, {y: 1, x: 2}]
->Js.Array2.filter(({y, x}) => {
  open Belt
  
  switch arr[y] {
  | Some(arrY) => arrY[x]->Option.isSome
  | None => false
  }
})
->Js.log
1 Like

I’d write it like this

let arr = [[1, 2], [3, 4]]

[{y: 0, x: 1}, {y: 1, x: 2}]
->Js.Array2.filter(({y, x}) =>
  arr
  ->Belt.Array.get(y)
  ->Belt.Option.flatMap(Belt.Array.get(_, x))
  ->Belt.Option.isSome
)
->Js.log
2 Likes