Skip to main content

window()

window<T>(array, size): T[][]

Creates a sliding window array of consecutive elements.

Returns an array of overlapping subarrays of the specified size, each shifted by one element from the previous.

๐Ÿ’Ž Why is this a Hidden Gem?

Creates sliding windows over arrays. Instead of writing error-prone for loops with array[i] and array[i+1], get clean tuples like [[1,2,3], [2,3,4], [3,4,5]]. Perfect for moving averages, trend detection, and comparing consecutive elements.


Type Parametersโ€‹

T: Tโ€‹

The type of elements in the array.


Parametersโ€‹

array: readonly T[]โ€‹

The source array to process.

size: numberโ€‹

The size of each window (must be a positive integer).


Returns: T[][]โ€‹

An array of subarrays, each containing size consecutive elements.


Throwsโ€‹

RangeError When size is not a positive integer.


Sinceโ€‹

2.0.0


Performanceโ€‹

O(nร—m) time & space, pre-allocated array, early return when size > length.


Also known asโ€‹

aperture (Ramda) ยท sliding (Effect) ยท window (es-toolkit) ยท โŒ (Lodash, Remeda, Radashi, Modern Dash, Antfu)


Exampleโ€‹

window([1, 2, 3, 4, 5], 3);
// => [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

How it works?โ€‹

Window creates overlapping subarrays by sliding one element at a time. Unlike chunk which splits without overlap, window preserves continuity between groups.

Window vs Chunkโ€‹

OperationOverlapOutput for [1,2,3,4,5] size 3
window(arr, 3)Yes[[1,2,3], [2,3,4], [3,4,5]]
chunk(arr, 3)No[[1,2,3], [4,5]]

Use Casesโ€‹

Detecting changes between consecutive values ๐Ÿ“Œโ€‹

Compare adjacent elements to identify transitions, changes, or deltas in sequences. Perfect for tracking state changes, price movements, or any sequential comparisons.

const temperatures = [18, 19, 22, 21, 25, 24];

const changes = window(temperatures, 2).map(([prev, curr]) => curr - prev);
// => [1, 3, -1, 4, -1]

const biggestJump = Math.max(...changes);
// => 4 (between 21 and 25)

Pairwise operations on sequencesโ€‹

Process elements in pairs for comparisons, validations, or transformations. Essential for route calculations, interval analysis, or sequential validations.

const waypoints = ["Paris", "Lyon", "Marseille", "Nice"];

const legs = window(waypoints, 2);
// => [["Paris", "Lyon"], ["Lyon", "Marseille"], ["Marseille", "Nice"]]

const routes = legs.map(([from, to]) => `${from} โ†’ ${to}`);
// => ["Paris โ†’ Lyon", "Lyon โ†’ Marseille", "Marseille โ†’ Nice"]

Moving averages for data smoothingโ€‹

Calculate rolling averages to smooth out fluctuations and reveal underlying trends. Essential for financial analysis, sensor data processing, and performance monitoring.

const stockPrices = [100, 102, 98, 105, 110, 108];

const movingAvg = window(stockPrices, 3).map(
(w) => w.reduce((a, b) => a + b, 0) / w.length
);
// => [100, 101.67, 104.33, 107.67]