Skip to main content

initial()

initial<T>(array): T[]

Gets all but the last element of array.

DEPRECATED

Use array.slice(0, -1) directly instead.

Reason:
Native equivalent method now available


Type Parameters​

T: T​

The type of elements in the array.


Parameters​

array: T[]​

The array to query.


Returns: T[]​

A new array with all elements except the last.


See Also​


Since​

2.0.0


Also known as​

dropLast (Remeda) · init (Ramda, Effect) · initial (Lodash, es-toolkit) · ❌ (Radashi, Modern Dash, Antfu)


Example​

const numbers = [1, 2, 3, 4, 5];

// ❌ Deprecated approach
const withoutLast = initial(numbers);
console.log(withoutLast); // [1, 2, 3, 4]

// βœ… Recommended approach
const withoutLastNative = numbers.slice(0, -1);
console.log(withoutLastNative); // [1, 2, 3, 4]

How it works?​

Gets all but the last element of array. Deprecated: Use array.slice(0, -1) directly.

Native Equivalent​

// ❌ initial(arr)
// βœ… arr.slice(0, -1)

Use Cases​

Get all but last element πŸ“Œβ€‹

Get array without the last element.

const items = [1, 2, 3, 4, 5];
items.slice(0, -1);
// => [1, 2, 3, 4]

Process all but current​

Get previous items excluding the current one.

const history = ["page1", "page2", "page3"];
history.slice(0, -1);
// => ["page1", "page2"]

Remove trailing element​

Create new array without the last item.

const path = ["home", "docs", "file.txt"];
path.slice(0, -1);
// => ["home", "docs"]