To copy a portion or part (from a start
index to an end
index) from an array, you can use the slice()
array method in JavaScript.
Let's say we have an array of names like this,
// names array
const namesArr = ["Roy", "Aleena", "Rachael", "John", "Lily"];
Now let's copy the items from index 1
through index 3
using the slice()
method by passing the start index as the first argument and the end index as the second argument to the method.
The only thing to note is that if we provide 1
as the start index and 3
as the end index we won't get the item at index 3
, So we have to pass index 4
as the end index so that item at index 3
is included.
It can be done like this,
// names array
const namesArr = ["Roy", "Aleena", "Rachael", "John", "Lily"];
// copy items from index 1 to index 3
// using the slice() array method
// by passing 1 as the start index
// and 4 as the end index
// here item at index 4 is not included
const newArr = namesArr.slice(1, 4);
console.log(newArr); // ["Aleena", "Rachael", "John"]
- The method returns a new array with copied contents.
See this example live in JSBin.