A sample array
For today’s article, let’s imagine that we have an array of wizard names.
let wizards = ['Merlin', 'Gandalf', 'Ursula', 'Radagast'];
We want to break this into two arrays: one with
Gandalf, and another with
Array.slice() method copies a segment of an array into a new one, leaving the original untouched.
The first argument is the array index to start at, and the second is the index to end on. Both are optional. If you omit the start index, it will start at the beginning. If you omit the end index, it will go to the end.
To split our
wizards array in two, we would do something like this.
let wizardsFirst = wizards.slice(0, 2); let wizardsSecond = wizards.slice(2);
Array.splice() method does a lot. You can use it to delete, replace, and add items to an array at specific indexes. Unlike
Array.slice(), it will modify the original array.
The first, start, is the index of the item you want to modify in the array. It’s the only required argument.
If we pass in
2 as an argument,
Array.splice() will “cut” the array in two, starting with the item at index
2. It returns the subset of the array, and removes it from the original.
let moreWizards = wizards.splice(2);