Skip to main content

Retrieving Collection Parts

Sometimes you do not need a whole array. You need a part of it: a range of elements, the first or last few, pieces of equal size, or a moving window of neighbours.

Arrays have one method for all of this: slice(). words.slice(low, high) gives the elements from index low up to, but not including, index high. Leave out high to go to the end. A negative index counts back from the end.

  • arr.slice(low, high) — from index low up to, but not including, high
  • arr.slice(0, n) — the first n elements
  • arr.slice(n) — everything from index n to the end
  • arr.slice(-n) — the last n elements

slice() always builds a new array and copies the chosen elements into it. Changing the copy does not change the original, and changing the original does not change the copy. In some other languages the same operation gives a view that shares memory with the original — here it never does.

There is no built-in take, drop, chunked or windowed. For those jobs this lesson uses slice() with computed bounds, a for loop, or a small generic helper function.

Most examples on this page use the same data: the words one two three four five six.


Slice

Slicing means taking the elements at some chosen positions.

For a run of neighbouring positions, use slice(): words.slice(1, 4) gives the elements at indexes 1, 2 and 3. Remember that the end index is excluded: to get the elements at indexes 1 to 3 you write slice(1, 4).

slice() cannot skip elements. To take every second element, or elements at positions you list yourself, use a for loop, or map() over an array of indexes.

Slice a range

words.slice(1, 4) starts at index 1 and stops before index 4. The result has 3 elements: [ 'two', 'three', 'four' ]. It is a new array, so a change to it would not touch words.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five, six. Use slice() to take the elements from index 1 up to, but not including, index 4. Print the result.
Output: TypeScript file and captured output
Slice a range

Slice with a step

To take every second element, a for loop with i += 2 visits indexes 0, 2 and 4 and collects the words. words.filter((_, i) => i % 2 === 0) gives the same result, but it looks at every element instead of jumping over them.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five, six. Use a for loop that goes from index 0 to index 4 in steps of 2 and pushes each element to a new array. Print the result.
Output: TypeScript file and captured output
Slice with a step

Slice by a list of indices

The positions 3, 5 and 0 are stored in an array of numbers. map() picks the word at each position, so the result comes out in the order of the indexes.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five, six and an array of indexes 3, 5, 0. Use map() over the indexes to collect the words at those positions, in that order. Print the result.
Output: TypeScript file and captured output
Slice by a list of indices

Take and Drop

Take means keep a number of elements from one end. Drop means throw away a number of elements from one end and keep the rest.

Both are slice() calls. words.slice(0, 3) takes the first 3 elements and words.slice(-3) takes the last 3. words.slice(1) drops the first element and words.slice(0, -5) drops the last 5.

There are also conditional versions: takeWhile, takeLastWhile, dropWhile and dropLastWhile. These do not count elements. They walk from one end and stop at the first element that fails a condition. There are no built-in versions, so a small generic helper does the job: it finds the index where the condition stops holding and returns slice() from that index.

Take the first or last n elements

words.slice(0, 3) keeps the first 3 words. words.slice(-3) keeps the last 3, because a negative start counts back from the end.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five, six. Use slice() to get the first 3 elements and the last 3 elements. Print both results on separate lines.
Output: TypeScript file and captured output
Take the first or last n elements

Drop the first or last n elements

words.slice(1) skips the first word. words.slice(0, -5) skips the last 5 words, so only one is left.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five, six. Use slice() to get everything except the first element, and everything except the last 5 elements. Print both results on separate lines.
Output: TypeScript file and captured output
Drop the first or last n elements

Take while a condition holds

takeWhile keeps words from the start until it meets a word that starts with f. takeLastWhile keeps words from the end until it meets three. startsWith() checks the start of a string.

Prompt
Write a TypeScript program with generic takeWhile and takeLastWhile helpers that take an array and a condition function. takeWhile keeps elements from the start while the condition holds; takeLastWhile does the same from the end. Use them on the words one, two, three, four, five, six: keep from the start while the word does not start with f, and keep from the end while the word is not three, then print both results.
Output: TypeScript file and captured output
Take while a condition holds

Drop while a condition holds

dropWhile skips the 3-letter words at the start and keeps everything from three on. dropLastWhile skips words from the end while they contain the letter i. includes() checks whether a string holds a piece of text.

Prompt
Write a TypeScript program with generic dropWhile and dropLastWhile helpers that take an array and a condition function. dropWhile skips elements from the start while the condition holds and keeps the rest; dropLastWhile does the same from the end. Use them on the words one, two, three, four, five, six: skip from the start while the word has 3 letters, and skip from the end while the word contains the letter i, then print both results.
Output: TypeScript file and captured output
Drop while a condition holds

Chunked

Chunking means cutting an array into pieces of the same size. The last piece may be shorter when the elements do not divide evenly.

There is no built-in chunk method, but the helper is short: step through the array with i += size and push items.slice(i, i + size) each time. slice() never reads past the end of the array, so the short last piece comes out right on its own.

The result is an array of arrays, and every piece keeps its own brackets. Node.js prints this one on a single line: [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ], [ 9, 10, 11 ], [ 12, 13 ] ].

To work on each piece right away, chain a map() onto the chunks.

Split into chunks of 3

The numbers 0 to 13 are cut into pieces of 3. The last piece has only 2 elements: [ 12, 13 ].

Prompt
Write a TypeScript program with a generic chunked helper that cuts an array into pieces of a given size, keeping a shorter last piece. Use it on the numbers 0 to 13 with a size of 3 and print the array of chunks.
Output: TypeScript file and captured output
Split into chunks of 3

Sum each chunk

The same chunks, but each one is added up with reduce(). Only the sums are kept: [ 3, 12, 21, 30, 25 ].

Prompt
Write a TypeScript program with a generic chunked helper that cuts an array into pieces of a given size. Use it on the numbers 0 to 13 with a size of 3, then map each chunk to its sum with reduce() and print the array of sums.
Output: TypeScript file and captured output
Sum each chunk

Windowed

A window is a group of neighbouring elements. Windowing slides the group along the array and collects every position. Unlike chunks, windows overlap.

There is no built-in windowed. A for loop with items.slice(i, i + size) does it. A small generic windowed helper makes it reusable. With a step, the window moves several positions at a time. With partial set to true, a shorter window at the end is kept instead of being thrown away.

A window of 2 that moves 1 step is the same as pairing each element with the next one. That is a loop that stops one element before the end.

Windows of 3

The window has 3 words and moves 1 position each time. The loop stops when a full window no longer fits, so there are 3 windows. The result is an array of arrays, and Node.js prints this one over several lines, one window per line.

Prompt
Write a TypeScript program with a generic windowed helper that takes an array and a window size and returns every group of that many neighbouring elements, moving one position at a time. Use it with size 3 on the words one, two, three, four, five and print the result.
Output: TypeScript file and captured output
Windows of 3

Windows with a step and partial windows

The window has 3 numbers and moves 2 positions each time. Because partial is true, the last window [ 9, 10 ] is kept even though it is short.

Prompt
Write a TypeScript program with a generic windowed helper that takes an array, a window size, a step and a partial flag. It moves step positions between windows, and when partial is true it also keeps a shorter window at the end. Use it on the numbers 1 to 10 with size 3, step 2 and partial set to true, then print the result.
Output: TypeScript file and captured output
Windows with a step and partial windows

Sum each window

Every window of 3 neighbours is added up with reduce(). Only the sums are kept: [ 6, 9, 12 ].

Prompt
Write a TypeScript program that makes an array of the numbers 1 to 5. Loop over every window of 3 neighbouring elements, add the window up with reduce() and push the sum to a new array. Print the array of sums.
Output: TypeScript file and captured output
Sum each window

Pair each element with the next one

The first loop builds a pair from each word and its neighbour. A pair is a tuple, the type [string, string]. The second loop compares the same neighbours and records whether the first word is longer than the second.

Prompt
Write a TypeScript program that makes an array of the words one, two, three, four, five. Loop over it and pair each element with the one after it, using a tuple type [string, string], and print the array of pairs. Then loop again and, for each pair of neighbours, record whether the first word is longer than the second. Print the array of booleans.
Output: TypeScript file and captured output
Pair each element with the next one