Skip to main content

Array Mutators

Array mutators transform arrays before validation. They modify the array structure and order without changing the data type.


All Mutators


Ordering

flip()

Reverse the order of array elements

v.array(v.string()).flip()
// Input: ["a", "b", "c"] → Output: ["c", "b", "a"]

reverse()

Alias for flip(). Reverse the order of array elements

v.array(v.string()).reverse()
// Input: ["a", "b", "c"] → Output: ["c", "b", "a"]

sort(direction?, key?)

Sort array elements. For objects, specify a key to sort by.

// Sort strings/numbers
v.array(v.string()).sort("asc")
// Input: ["c", "a", "b"] → Output: ["a", "b", "c"]

v.array(v.int()).sort("desc")
// Input: [3, 1, 2] → Output: [3, 2, 1]

// Sort objects by key
v.array(v.object({ name: v.string() })).sort("asc", "name")
// Input: [{ name: "Zoe" }, { name: "Alice" }] → Output: [{ name: "Alice" }, { name: "Zoe" }]

Parameters:

  • direction (optional): "asc" or "desc" (default: "asc")
  • key (optional): Key to sort by for object arrays

Deduplication

onlyUnique()

Remove duplicate values from the array

v.array(v.string()).onlyUnique()
// Input: ["a", "b", "c", "a", "b"] → Output: ["a", "b", "c"]

Note: This removes duplicates but doesn't validate uniqueness. Use unique() validator to ensure all items are unique.


Examples

Sort and Deduplicate

const schema = v.array(v.string())
.sort("asc")
.onlyUnique();

const result = await validate(schema, ["c", "a", "b", "a", "c"]);
// Result: { isValid: true, data: ["a", "b", "c"] }

Reverse Order

const schema = v.array(v.int())
.flip();

const result = await validate(schema, [1, 2, 3]);
// Result: { isValid: true, data: [3, 2, 1] }

Sort Objects

const schema = v.array(v.object({
name: v.string(),
age: v.int()
}))
.sort("asc", "age");

const result = await validate(schema, [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 }
]);
// Result: { isValid: true, data: [{ name: "Jane", age: 25 }, { name: "John", age: 30 }] }

Mutator Chain

const schema = v.array(v.string())
.sort("asc") // Sort first
.onlyUnique() // Then remove duplicates
.flip(); // Finally reverse

const result = await validate(schema, ["c", "a", "b", "a", "c"]);
// Result: { isValid: true, data: ["c", "b", "a"] }

Important Notes

Mutators Run Before Validation

v.array(v.string())
.onlyUnique() // Mutator: Remove duplicates
.unique() // Validator: Check all are unique

Sort Direction

v.array(v.int()).sort("asc")   // Ascending: 1, 2, 3
v.array(v.int()).sort("desc") // Descending: 3, 2, 1

Object Sorting

When sorting object arrays, provide the key:

v.array(v.object({ age: v.int() })).sort("asc", "age")

See Also