In Postgresql 9.6, is there a clean way to multiply corresponding elements within two equally sized arrays?
For example
a = [1,2,9,4,5]
b = [5,8,4,0,12]
function(a, b) would return [5, 16, 36, 0, 60].
I'd prefer it as a function like this, since it'd be used in multiple places.
Best Answer
Parallel Unnest
What you want is something like this with parallel-unnest. Here we use the
ARRAY()
constructor rather thanarray_agg()
Creating our own function
In functional programming, we call this
zip
, and you'd use that in a language with primitive functional support like Python, or the like. In languages with more advanced functional support, like Haskell, you'd usezipWith
or Ramda.jsR.zipWith()
This will return an array sized to the greater of
ex1
, orex2
. You can put this in a function like this,Note: this won't work if there isn't an operator
*
defined for the type.