Q:

Fetch values for a single field across all entries in a section

I have a section "Hotel Room" with a field "Sleeps" (number). There is no limit on the values that can be entered. On the frontend I want a list of all existing entered values for this field. So if I have these four entries:

sleeps=2
sleeps=2
sleeps=8
sleeps=10

I want an array [2, 2, 8, 10] to iterate over. Bonus points for unique/distinct values, but I'm well aware I can add a Twig filter to array_unique() it.
Is this possible using Craft's craft.entries lookups within Twig?

A:

Getting that array is simple. Prepare an empty array, then loop through your entries and merge the "Sleeps" fields value to it.
To get your array with the unique values, you basically do the same but also save the value as the key on each iteration. If a key already exists in the array the key/value pair gets overwritten (→ good for you)!
There's a strange behaviour that setting custom numeric keys doesn't work with Twig, that's why I composed a string out of the value.
{# Prepare variables #}
{% set myArray1 = [] %}
{% set myArray2 = [] %}

{# Loop through entries of the "Hotel Room" section #}
{% for entry in craft.entries.section('hotelRoom') %}

    {% set value = entry.sleeps %}

    {% set myArray1 = myArray1|merge([value]) %}
    {% set myArray2 = myArray2|merge({ ('key' ~ value): value }) %}

{% endfor %}

