The slice method returns a new array with a copied slice from the original array.
Syntax:
arr.slice([start[, end]])
start
refers Zero-based index. If start
is undefined, slice
starts from the index 0.
In end
, slice extracts up to but not including end.
Its too theoretically right π, lets understand by few examples.
Using two arguments β :
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice(2,4);
console.log(newArr); // ["π½", "π"]
Without arguments, you get a copy of the full array β
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice();
console.log(newArr); // ["π", "π", "π½", "π", "π"]
Using one argument, you get a copy from the specified index to the end of the array β
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice(3);
console.log(newArr); // ["π", "π"]
Index can also be negative, in which case the starting index is calculated from the end β
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice(2,-2);
console.log(newArr); // ["π½"]
If start
is greater than the index range of the sequence, an empty array is returned β
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice(6);
console.log(newArr); // []
If end
is greater than the length of the sequence, slice extracts through to the end of the sequence β
const arr = ['π', 'π', 'π½', 'π', 'π'];
const newArr = arr.slice(1,9);
console.log(newArr); // ["π", "π½", "π", "π"]
slice() method can also be used for strings β
const arr = 'suprabha';
const newArr = arr.slice(0,3);
console.log(newArr); // "sup"
Note: π§¨
Slice is immutable and Splice mutates the array.
Reference π§
π Twitter | π©π»βπ» Suprabha.me | π Instagram |
Top comments (4)
Nice refresher Suprabha.
Here are two lists that people may find useful:
mutator array methods:
push (back add)
pop (back remove)
unshift (front add)
shift (front remove)
splice
sort
reverse
fill
forEach
non-mutator array methods:
concat
join
filter
slice
map
reduce
find
findIndex
some
every
includes
flat
flatMap
Hahaha I can understand. I fixed that π€ͺ
Very nicely explained
I tried to join, but wouldn't able to join to the group.