The slice
method in an array
returns a shallow copy of a portion of the array based on the start
and end
index passed.
3 Uses for Array Slice in JavaScript
- Copy an array.
- Get the first N array.
- Remove an element at a specific index.
Here’s a brief refresher on the slice method:
- Both
start
andend
is an optional argument. - By default the
start
is0
andend
isarray.length
end
of an index is not considered. This means if youslice
an array passingstart
as0
andend
as5
, then elements from0th
to4th
index will be copied.- The
slice
doesn’t affect thesource
array from which we are performingslice
. - It only creates a
shallow copy
. - We can also give a negative value for the
start
andend
index, which indicates an offset from the end of the array. So, we can have a -1 point to last element.
var numbers = [0, 1, 2, 3, 4, 5];
var newNumbers = numbers.slice(1,4);
newNumbers; //[1,2,3]
How to Use Array Slice in JavaScript
Below are some common ways you can use the array slice method in JavaScript.
1. Use Array Slice to Copy an Array
var numbers = [0, 1, 2, 3, 4, 5];
var copiedNumbers = numbers.slice(0, numbers.length);
copiedNumbers; // [0, 1, 2, 3, 4, 5]
By default, the start index is 0 and the end index is the length of the array. By applying that, we see:
var numbers = [0, 1, 2, 3, 4, 5];
var copiedNumbers = numbers.slice();
copiedNumbers; // [0, 1, 2, 3, 4, 5]
2. Use Array Slice to Get the First N Array
This is similar to copying an array. Instead of passing the end
index value as arrayLength
, pass end
index as n.
function firstNItems(n, numbers =[] ) {
if(n >= 0) {
return numbers.slice(0, n);
}
return [];
}
firstNItems(0, [1,2,3]); // []
firstNItems(2, [1,2,3]); // [1,2]
3. Use Array Slice to Remove an Element at a Specific Index
Using the shift
and pop
method, you can remove an element at the front and end of the array respectively. But there is no method to remove an element at a specific index. For that, you can use the slice method.
This will allow you to do the following:
- Create an array that contains all elements of the array before the index.
- Create an array that contains all elements of the array after the index.
- Join two arrays.
function removeElementAt(arr, index) {
let frontPart = arr.slice(0, index);
let lastPart = arr.slice( index+1 ); // index to end of array
return [...frontPart, ...lastPart];
}
let numbers = [1,2,3,4,5];
removeElementAt(numbers, 2); [1,2,4,5];