slice() – Return Sub-Array
array1.slice()
array1.slice(, start)
array1.slice(, start, end)
array1
is an array of elementsstart
is the starting index (inclusive) from which slicing happensend
is the ending index (exclusive) upto which slicing happens
slice() method returns a shallow copy of the given array from start
index upto end
index
slice() method does not modify the original array array1
Examples
1. slice entire array
const array1 = [2, 4, 8, 16, 32, 64, 128, 256];
const output = array1.slice();
console.log('Original Array : ' + array1);
console.log('Sliced Array : ' + output);
If no arguments are passed to slice(), then slice() method returns a copy of the original array
2. slice array from a specific start
const array1 = [2, 4, 8, 16, 32, 64, 128, 256];
const start = 5;
const output = array1.slice(start);
console.log('Original Array : ' + array1);
console.log('Sliced Array : ' + output);
3. slice array from a specific start index upto specific end index
const array1 = [2, 4, 8, 16, 32, 64, 128, 256];
const start = 2;
const end = 6;
const output = array1.slice(start, end);
console.log('Original Array : ' + array1);
console.log('Sliced Array : ' + output);