Sidechair

array.unshift()

Browse the reference

Inserts a value at the start of an array; every existing item moves up one position.

Try it in the editor

After array.unshift(a, x) the value x is at index 0 and the old first item is at index 1. Used with array.pop() it keeps the newest value in front and drops the oldest at the back.

Pushing the array past 100,000 items stops the script with an error, and a value of the wrong type is rejected.

Syntax

Pine Script
array.unshift(id: any array type, value: series <type of the array's elements>) -> void
array.unshift(value: series <type of the array's elements>) -> void

Arguments

NameTypeDefaultDescription
idany array typerequiredThe array that receives the new item at its front. Existing items move up by one.
valueseries <type of the array's elements>requiredThe item to store, or the item to look for. It has to match the type of the array's items.

Returns

Nothing.

Remarks

  • Inserting at the front costs more as the array grows, because every item moves. For long arrays prefer array.push().

Example

Pine ScriptNewest firstOpen in editor
//@version=6
indicator("array.unshift: newest first", overlay = true)
var recent = array.new_float()
array.unshift(recent, close)
if array.size(recent) > 3
    array.pop(recent)
plot(array.get(recent, 0), "Newest", color.blue)
plot(array.get(recent, array.size(recent) - 1), "Oldest of 3", color.gray)

See also

Runs on Sidechair