Search code examples
arraysgoogle-sheetsfilterflattengoogle-query-language

Converting a 2D range into a 1D array with spaces in Google Sheets


I would like to convert a range/array like this

| Fruit     | Strawberry |
| Fruit     | Blueberry  |
| Fruit     | Banana     |
| Vegetable | Lettuce    |
| Vegetable | Cucumber   |
| Vegetable | Carrot     |
| Vegetable | Celery     |
| Dairy     | Milk       |
| Dairy     | Butter     |
| Dairy     | Cheese     |

into a 1D array with spaces separating categories like this

| Fruit      |
| Banana     |
| Blueberry  |
| Strawberry |
|            |
| Vegetable  |
| Carrot     |
| Celery     |
| Cucumber   |
| Lettuce    |
|            |
| Dairy      |
| Butter     |
| Cheese     |
| Milk       |

in Google Sheets. I can easily achieve a 1D array without spaces with =UNIQUE(FLATTEN(A2:B11)) where A2:B11 is the original data range; however, I am not able to get the desired spaces separating categories.

Could anyone help?

Here's the example sheet: https://docs.google.com/spreadsheets/d/1ww1fkDRBUsVx-pLDJ4Qo9VXlzAZDEyYoANRdRK7Yum4/edit?usp=sharing


Solution

  • try:

    =INDEX(QUERY(FLATTEN(TRANSPOSE(QUERY({A2:B, ROW(A2:A)},
     "select max(Col2) group by Col3 pivot Col1"))), 
     "where Col1 is not null", ))
    

    enter image description here


    update:

    =INDEX(SUBSTITUTE(QUERY(FLATTEN(IFERROR(SPLIT(FLATTEN(TRANSPOSE(
     QUERY({"♦×"&A2:A, B2:B, ROW(A2:A)},
     "select max(Col2) group by Col3 pivot Col1"))), "×"))), 
     "where Col1 is not null offset 2", ), "♦", ))
    

    enter image description here