ENUMS
PROGRAMMING
CODING
JAVASCRIPT
JAVA

How to get all enum values as an array

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Getting all enum values as an array is a common need when populating dropdowns, validating input, or iterating over every possible option. The approach varies by language because each language implements enums differently. In TypeScript, use Object.values() with filtering. In Java, call EnumType.values(). In Python, iterate the enum class directly. In C#, use Enum.GetValues(). In Swift, conform to CaseIterable. This article shows the idiomatic approach for each major language.

TypeScript / JavaScript

TypeScript enums compile to objects with both forward and reverse mappings for numeric enums, which requires filtering:

typescript
1// Numeric enum
2enum Direction {
3  Up = 0,
4  Down = 1,
5  Left = 2,
6  Right = 3,
7}
8
9// Object.values includes reverse mappings: ["Up", "Down", "Left", "Right", 0, 1, 2, 3]
10// Filter to get only the string keys or only the numeric values
11const names = Object.keys(Direction).filter((k) => isNaN(Number(k)));
12console.log(names); // ["Up", "Down", "Left", "Right"]
13
14const values = Object.values(Direction).filter((v) => typeof v === "number");
15console.log(values); // [0, 1, 2, 3]
16
17// String enum — no reverse mapping issue
18enum Color {
19  Red = "RED",
20  Green = "GREEN",
21  Blue = "BLUE",
22}
23
24const colorValues = Object.values(Color);
25console.log(colorValues); // ["RED", "GREEN", "BLUE"]

const enum Caveat

typescript
1// const enums are inlined at compile time — no runtime object exists
2const enum Status {
3  Active,
4  Inactive,
5}
6
7// Object.values(Status) — ERROR: 'const' enums can only be used in property access
8// Solution: use a regular enum instead of const enum

Java

Java enums have a built-in values() method generated by the compiler:

java
1public enum Planet {
2    MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
3}
4
5// Get all values as an array
6Planet[] planets = Planet.values();
7// [MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE]
8
9// Convert to a List
10List<Planet> planetList = Arrays.asList(Planet.values());
11// Or with streams
12List<Planet> list = Arrays.stream(Planet.values()).collect(Collectors.toList());
13
14// Iterate
15for (Planet p : Planet.values()) {
16    System.out.println(p.name() + " ordinal=" + p.ordinal());
17}
18
19// EnumSet — optimized Set for enums
20EnumSet<Planet> innerPlanets = EnumSet.of(Planet.MERCURY, Planet.VENUS,
21                                          Planet.EARTH, Planet.MARS);
22EnumSet<Planet> allPlanets = EnumSet.allOf(Planet.class);

Enums with Fields

java
1public enum HttpStatus {
2    OK(200), NOT_FOUND(404), INTERNAL_ERROR(500);
3
4    private final int code;
5    HttpStatus(int code) { this.code = code; }
6    public int getCode() { return code; }
7}
8
9int[] codes = Arrays.stream(HttpStatus.values())
10    .mapToInt(HttpStatus::getCode)
11    .toArray();
12// [200, 404, 500]

Python

Python's enum.Enum class is iterable, so you can convert it directly:

python
1from enum import Enum
2
3class Color(Enum):
4    RED = 1
5    GREEN = 2
6    BLUE = 3
7
8# Get all members as a list
9all_colors = list(Color)
10# [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
11
12# Get names
13names = [c.name for c in Color]
14# ['RED', 'GREEN', 'BLUE']
15
16# Get values
17values = [c.value for c in Color]
18# [1, 2, 3]
19
20# Dict of name -> value
21color_dict = {c.name: c.value for c in Color}
22# {'RED': 1, 'GREEN': 2, 'BLUE': 3}
23
24# Lookup by value
25print(Color(2))       # Color.GREEN
26# Lookup by name
27print(Color['BLUE'])  # Color.BLUE

C#

csharp
1public enum Season
2{
3    Spring,
4    Summer,
5    Autumn,
6    Winter
7}
8
9// Get all values as an array
10Season[] seasons = (Season[])Enum.GetValues(typeof(Season));
11// Or with generics (.NET 5+)
12Season[] seasons = Enum.GetValues<Season>();
13
14// Get names
15string[] names = Enum.GetNames(typeof(Season));
16// ["Spring", "Summer", "Autumn", "Winter"]
17
18// Convert to List
19List<Season> seasonList = Enum.GetValues<Season>().ToList();
20
21// Iterate
22foreach (Season s in Enum.GetValues<Season>())
23{
24    Console.WriteLine($"{s} = {(int)s}");
25}

Flags Enum

csharp
1[Flags]
2public enum Permissions
3{
4    None = 0,
5    Read = 1,
6    Write = 2,
7    Execute = 4,
8    All = Read | Write | Execute
9}
10
11// GetValues includes composite values
12Permissions[] all = Enum.GetValues<Permissions>();
13// [None, Read, Write, Execute, All]

Swift

Swift enums use the CaseIterable protocol:

swift
1enum Suit: String, CaseIterable {
2    case hearts, diamonds, clubs, spades
3}
4
5// Get all cases as an array
6let allSuits: [Suit] = Suit.allCases
7// [.hearts, .diamonds, .clubs, .spades]
8
9// Get raw values
10let rawValues = Suit.allCases.map { $0.rawValue }
11// ["hearts", "diamonds", "clubs", "spades"]
12
13// Count
14print(Suit.allCases.count) // 4
15
16// Iterate
17for suit in Suit.allCases {
18    print(suit)
19}

Enums with Associated Values

swift
1// CaseIterable does NOT work automatically with associated values
2enum Barcode {
3    case upc(Int, Int, Int, Int)
4    case qrCode(String)
5}
6// Barcode.allCases — compile error
7// You must implement allCases manually for associated-value enums

Kotlin

kotlin
1enum class Direction {
2    NORTH, SOUTH, EAST, WEST
3}
4
5// Get all values
6val directions: Array<Direction> = Direction.values()
7// Or using entries (Kotlin 1.9+)
8val directions: List<Direction> = Direction.entries
9
10// Get names
11val names = Direction.entries.map { it.name }
12
13// Lookup by name
14val dir = Direction.valueOf("NORTH") // Direction.NORTH

Common Pitfalls

  • TypeScript numeric enums have reverse mappings: Object.values(NumericEnum) returns both string keys and numeric values. You must filter by type to get only the values you want. String enums do not have this issue.
  • Java values() creates a new array each call: Every call to EnumType.values() allocates a new array. In performance-critical code, cache the result in a static field rather than calling it repeatedly in loops.
  • C# Enum.GetValues returns Array, not a typed array: Before .NET 5, Enum.GetValues(typeof(T)) returns an untyped Array that must be cast. Use the generic Enum.GetValues<T>() on .NET 5+ for a typed result.
  • Swift CaseIterable does not work with associated values: Enums with associated values (e.g., case item(String)) cannot automatically conform to CaseIterable. You must provide a manual allCases implementation.
  • Python Enum iteration order matches definition order: Members iterate in the order they are defined in the class body. This is guaranteed by the language (Python 3.6+), but relying on it for logic may confuse readers who expect alphabetical order.

Summary

LanguageMethodReturn Type
TypeScriptObject.values(Enum) (filter for string enums)string[] or number[]
JavaEnumType.values()EnumType[]
Pythonlist(EnumClass)list[EnumClass]
C#Enum.GetValues<T>()T[]
SwiftEnumType.allCases[EnumType]
KotlinEnumType.entriesList<EnumType>

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.