What is a TypedArray in JavaScript?
Prior to delving into the slice method, it’s essential to first provide a brief definition of the term TypedArray.
JavaScript typically employs dynamic arrays capable of holding various data types, including numbers, strings, objects, and more. However, in scenarios involving binary data, images, file data, or WebGL, there arises a need for fixed-type raw binary data arrays. This is where TypedArrays come into play.
Examples of TypedArrays include:
- Int8Array: 8-bit signed integers
- Uint8Array: 8-bit unsigned integers
- Float32Array: 32-bit floating point numbers
What is the slice method in a TypedArray?
The slice function utilized by a TypedArray (such as Int8Array, Uint8Array, Float32Array, etc.) creates a new TypedArray that contains a portion of the original array, leaving the original array unchanged.
It closely resembles the slice function that you are already acquainted with in standard JavaScript arrays.
In summary,
- It extracts a portion of the TypedArray.
- It returns a new TypedArray of the same type.
- The original TypedArray remains unchanged.
Syntax:
typedArray.slice(begin, end);
- begin: The index to begin slicing (inclusive). If omitted, 0 is the default.
- end: The index to stop slicing (exclusive). If omitted, slices to the end of the array.
- Return value: It returns a new array that contains some selected part of the array.
How slice Works on a TypedArray?
The slice function duplicates designated elements from a TypedArray and produces a new TypedArray of identical type containing the chosen elements.
The slice method works with TypedArray as follows:
- Allocates new memory space to create a new TypedArray.
- Copies values from the original TypedArray starting at the beginning index.
- Stops copying before it reaches the end index.
- Returns a completely new TypedArray with the copied values.
- The original TypedArray is not modified.
Example
const original = new Int16Array([100, 200, 300, 400, 500]);
const result = original.slice(1, 4);
console.log(result);
Output:
Int16Array [ 200, 300, 400 ]
Explanation:
- Started at index 1 (value = 200).
- Stopped before index 4 (value = 500).
- Copied values: 200, 300, 400 into a new Int16Array.
Examples of slice on TypedArrays
Example 1: Basic Usage
Example
const numbers = new Int16Array([10, 20, 30, 40, 50]);
const sliced = numbers.slice(1, 4);
console.log(sliced);
console.log(numbers);
Output:
Int16Array [ 20, 30, 40 ]
Int16Array [ 10, 20, 30, 40, 50 ]
Clarification:
- We commenced our slicing operation at index 1 and concluded just before index 4.
- As a result, it selected the values 20, 30, and 40.
Example 2: Omitting end
Example
const data = new Uint8Array([1, 2, 3, 4, 5, 6]);
const sliced = data.slice(3);
console.log(sliced);
Output:
Uint8Array [ 4, 5, 6 ]
Explanation:
In the absence of an end parameter, slicing continues up to the final element.
Example 3: Using negative indexes
Similar to arrays, the method slice also accommodates negative indices.
Example
const values = new Float32Array([2.5, 4.5, 6.5, 8.5]);
const sliced = values.slice(-3, -1);
console.log(sliced);
Output:
Float32Array [ 4.5, 6.5 ]
Explanation:
- -3 begins its count from the conclusion (specifically the third item from the end).
- -1 ceases its count just prior to the final element.
Why use slice on TypedArrays?
TypedArrays, which encompass types such as Uint8Array, Int16Array, and Float32Array, serve as the means to handle binary data within JavaScript. They enable the reading of files, images, audio, or data buffers sourced from WebSockets and WebGL through the use of TypedArrays.
Utilizing the slice method greatly enhances the experience of handling TypedArrays, as it allows you to:
- Extract a portion of your data into a separate TypedArray.
Consider a substantial data buffer, such as a sound recording stored in a Float32Array that contains thousands of individual samples, and suppose you only wish to manipulate a specific segment of this buffer.
const chunk = audioBuffer.slice(5000, 6000);
You now possess a fresh TypedArray that contains solely that specific segment.
- Ensure that your original data remains untouched.
The slice method does not modify the existing TypedArray; instead, it generates a new TypedArray.
As a result, you have the ability to slice, modify, or slice and remove elements from the new array, all while ensuring that your original data remains intact and free from corruption.
- Copying data easily
slice is a simple way to copy any TypedArray.
const copy = myData.slice();
Now copy is a new TypedArray with the same data.
- Work with protocols and chunks of data easily
- Network (WebSockets, Bluetooth, etc.) packets are binary payload packets of a large size and you are tasked to extract a header, body, checksum, etc.
- You can extract anything nicely with slice:
const header = packet.slice(0, 10);
const body = packet.slice(10, -2);
const checksum = packet.slice(-2);
- Facilitate the handling of graphics and audio processing
When working with things like:
- WebGL buffers
- Canvas image data
- Audio streams
- Machine learning tensors
Frequently, you may find yourself working with merely segments of the data. The slice method offers an effective and straightforward approach to obtain the specific portion you desire.
Conclusion
The slice function available in JavaScript TypedArrays is an excellent method for extracting a particular segment of your data, allowing you to create a new TypedArray for manipulation without altering the original. This method can be applied to various types of data, including images, audio, files, or raw binary information. Its usage is straightforward and if you need to obtain a specific part of your data, slice serves as an invaluable resource.
It resembles the slice function found in standard arrays; however, it is particularly user-friendly when applied to TypedArrays such as Uint8Array, Float32Array, Int16Array, among others.
In conclusion, if your goal is to handle segments of binary data safely and appropriately, then the slice method is an essential instrument in your arsenal of TypedArrays.
Frequently Asked Questions (FAQs)
- What does slice do in a TypedArray?
The slice function is a method that allows you to extract a segment of a TypedArray (such as Uint8Array, Float32Array, etc.) and create a new TypedArray with that segment, all while leaving the original array intact.
- Does slice modify the original TypedArray?
No. The original TypedArray remains unchanged since the slice function solely produces a fresh copy of the specified segment.
- What does slice(start, end) signify?
This signifies that:
- Begin the copying process from the starting index (inclusive)
- Cease the operation just prior to the ending index (exclusive)
In the absence of a specified end, the slice method will extract elements up to the conclusion of the TypedArray.
- Is it possible to utilize negative integers in the slice function?
Indeed, similar to standard arrays, it is possible to utilize negative indices to reference elements from the conclusion of the Typed Array.
Example:
typedArray.slice(-3, -1);
This operation extracts elements from the third-to-last position up to the second-to-last position.
- What kind of array is produced by the slice method?
It produces a new TypedArray of identical type. For instance, when you slice a Uint8Array, the result is another Uint8Array.
- Is it possible to duplicate the entire TypedArray by utilizing slice?
Yes, you can call it without any arguments:
const copy = typedArray.slice();
This gives you a complete copy of the original.
- What is the difference between slice and subarray?
- The slice returns a new TypedArray with copied data.
- The subarray returns a view into the same underlying memory buffer. If you change the subarray then the original TypedArray will also change.