Search code examples
arrayssumjsonata

Sum arrays element by element in JSonata


I need to sum 2 arrays element by element, considering also potential "null" in the data.

Here a body example:

{
  "response": {
    "doc": [
      {
        "channels": {
          "channel1": {
            "samples": [
              1,
              2,
              3,
              4,
              5
            ]
          },
          "channel2": {
            "samples": [
              null,
              null,
              3,
              4,
              null
            ]
          }
        }
      }
    ]
  }
}

What I need to obtain is an array as follows:

[null,null,6,8,null]

Any help is appreciated.

Thanks


Solution

  • You can sum the two arrays element by element using JSONata with the following expression:

    response.doc.{
        "result": $zip(channels.channel1.samples, channels.channel2.samples) ~> 
        $map(function($v, $i, $a) {
            $v[0] != null and $v[1] != null ? $v[0] + $v[1] : null
        })
    }
    

    Feel free to play with this expression on Stedi JSONata Playground