1

I have a 1-dimensional array of values in Postgres, such as:

[ "1", "4", "2", "5", "3", "6" ]

Is there a way to change this to a 2-D array?

[ ["1", "4"], ["2", "5"], ["3", "6"] ]

Now the dimensions are 3x2 instead of 1x6.

4
  • Did you try a cast? AS int[2][]? Commented Feb 6, 2020 at 0:04
  • @Bergi: that's bright, but it does not seem to work. Commented Feb 6, 2020 at 0:12
  • What if there is an uneven number of elements in the array? Commented Feb 6, 2020 at 0:13
  • @GMB Guaranteed not to be. Really what I'm trying to do is the last step of a transpose (it's a CodeWars problem where I can't see the solution). Since I wrote this I actually figured out how to get the transpose to work bypassing this particular step, but I'm still curious if there is a good way to do reshape essentially. Commented Feb 6, 2020 at 0:15

1 Answer 1

1

Use two aggregates:

select array_agg(arr order by ord)
from (
    select (ord+ 1) / 2 as ord, array_agg(arr) as arr
    from unnest(array[1,4,2,5,3,6]) with ordinality as u(arr, ord)
    group by 1
    ) s

or an array constructor:

select array(
    select array_agg(unnest)
    from unnest(array[1,4,2,5,3,6]) with ordinality
    group by (ordinality+ 1) / 2
    order by (ordinality+ 1) / 2
    )

Db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.