Arrays provide many methods. According to the MDN Web Docs documentation, the Array.slice() method, in particular, sends back a shallow copy of a certain part of an array to a brand new array object, that is selected from beginning to end (not including an end). And note that the original array is not modified.

Syntax

arr.slice([start], [end])

Example

let arr = ["t", "e", "s", "t"];
alert( arr.slice(1, 3) );
// e,s (copies from 1 to 3)
alert( arr.slice(-2) );
// s,t (copies from -2 to the end)

It returns a new array into which it copies the elements from index start to end (not including end). Note that both indices for start and end could be negative. In this case, the count will be carried out from the end of the array.

This is similar to the str.slice() string method but returns subarrays instead of substrings. Let's explore the use of the Array.slice() method.

Using

1. Simple copying

You can call slice with no arguments at all: arr.slice () creates a copy of the initial array. This is often used to create a copy of an array for further transformations that do not need to change the original array.  You need to call it with no arguments and save the result to a new variable.

Example

const isWatched = ['GameOfThrones', 'Breaking Bad']
const myFriendWatched = isWatched.slice()
myFriendWatched.push('American Gods')
console.log(isWatched)
// ['GameOfThrones', 'Breaking Bad']
console.log(myFriendWatched)
// ['GameOfThrones', 'Breaking Bad', 'American Gods']

2. The first target indexes of an initial array

To pull off the front of an array, we need to pass two arguments to the Array.slice() method. When both arguments are passed, the slice method returns a new array starting at the index of the first argument and it ends on the second argument -1 (minus one) of the initial array.

function useFirstIndexes(arr) {
  return arr.slice(0, 4);
}

3. The negative index of the initial array

Another way of using Array.slice() is grabbing the end of the initial array. In this case, we need to use a negative index. For instance, we want to grab only the last 3 items of our initial array.

function useLastThree(arr) {
  return arr.slice(-3);
}

4. Start from target index and with a target length

We'll apply this method when we want to use Array.slice() to pull off a segment of the array starting at any index. To realize this we need to translate from (begin, length), to (begin, end) by declaring a function:

function lengthSegment(arr, arrStart, arrLength) {
  return arr.slice(arrStart, arrStart + arrLength);
}

5. A new array, starting from the target index

If you want to extract the first element of the initial array and do some operation with it and return the rest of the array without mutating the initial array, use the example below.

function useTheFirstEl(initArr) {
  const usedItem = initArr[0];
  return initArr.slice(1);
}

6. Convert array-like objects into arrays

We can use the Array.slice() method to turn array-like objects into arrays. Say, like this:

function convert() {
  return Array.prototype.slice.call(args);
}
const alphabet = convert("x", "y", "z");
console.log(alphabet);
// ["x", "y", "z"]

In this example, the args of the convert() function is an array-like object. Inside the convert() function, we called the Array.slice() method to convert the args object into an array. Every argument we pass to the convert() function will be the elements of the new array.

Let's clear Array.prototype.slice.call() piece by piece:

Array - the base object name we aim at.

prototype - we can perceive it as a space for the name.

slice - it pulls out a part of an array and sends back a new array, without a starting and ending indices, i.e. just a copy of an array.

call - allows us to call up a function from one object and use it in the context of another.

Another common instance is conversion of a NodeList into an array, it goes something like this:

let arrLike = document.querySelectorAll("p");
const arr = Array.prototype.slice.call(arrLike);

Here we went with the document.querySelectorAll() to retrieve all nodes from the HTML document. This resulted in a NodeList object, that's an array-like object in fact. Afterwards, we applied the Array.slice() method to convert it into an array.

Sometimes, you may see the following syntax:

const arr = [].slice.call(document.querySelectorAll('p'));

Here we created the empty [] array and applied the Array.slice() method of the Array.prototype method via an empty array. Then we achieved the similar effect to the one with the direct Array.prototype.

Summary: 

Up to now, we have shown you how to use the JavaScript array method Array.slice(). The 3 key practical applications for it, though, are:

  1. cloning an array without modifying the initial array;

  2. copying a part of an array into a new array without modifying the initial array;

  3. converting array-like objects into arrays.

Test yourself

  • Task 1. Write a function that converts "your-first-message" to "yourFirstMessage". You need to remove all hyphens, and all words after them need to be capitalized.

Example:

kebabToCamel("border-radius") == 'borderRadius';
kebabToCamel("one-two-three") == 'oneTwoThree';
kebabToCamel("-kebab-case") == 'KebabCase';

Solution:

function kebabToCamel(string) {
  return (
    string
      .split("-")
      // splits 'your-first-message' into an array ['your', 'first', 'message']
      .map(
        // Converts to uppercase the first letters of all elements of the array except the first
        // converts ['your', 'first', 'message'] into ['your', First', 'Message']
        (word, index) =>
          index == 0 ? word : word[0].toUpperCase() + word.slice(1).join("")
      )
  );
  // convert ['your', First', 'Message'] into 'yourFirstMessaged'
}
  • Task 2. Prepare a phone number in the format (12)-346578-9012.

Solution:

function formatPhoneNumbers(numbers) {
  return `(${numbers.slice(0, 2)})-${numbers.slice(2, -4)}-${numbers.slice(
    -4
  )}`;
}
let numberForFormatting = "123465789012";
let formattedNumber = formatPhoneNumbers(numberForFormatting);
console.log(formattedNumber);
  • Task 3. Write a method that splits an array into parts of predetermined sizes. Expected Result: ([1, 2, 3, 4, 5], 2) => [[1, 2], [3, 4], [5]].

Solution:

function chunkArr(arr, size) {
  const chunkedArr = [];
  let index = 0;
  while (index < arr.length) {
    chunkedArr.push(arr.slice(index, size + index));
    index += size;
  }
  return chunkedArr;
}
const result = chunkArr([1, 2, 3, 4, 5], 2);
console.log(result);
  • Task 4. Write a function that creates an array from the unique values that are in each of the provided arrays.

const arr01 = ["b", "e", "c"];
const arr02 = ["b", "b", "e"];

Solution:

function intersection(...arr) {
  const result = arr[0].filter((el) => {
    const indexOfEl = arr[1].indexOf(el);
    if (indexOfEl >= 0) {
      return el;
    }
  });
  if (arr.length > 2) {
    intersection(result, ...arr.slice(2, arr.length));
  }
  return Array.from(new Set(result));
}

const result = intersection(arr01, arr02);
console.log(result);
  • Task 5. Copy an array into another array.

let arr1 = [11, 12, 13, 54, 65];

Solution:

let arr2 = arr1.slice();
console.log(arr2);
  • Task 6. Copy 'Cucumber' and 'Cabbage' into another array.

let vegetables = ['Potatoe', 'Cucumber', 'Сabbage', 'Сauliflower', 'Zucchini'];

Solution:

let newVegetables = vegetables.slice(1, 3)
// vegetables contains ['Potatoe', 'Cucumber', 'Сabbage', 'Сauliflower', 'Zucchini']
// newVegetables ['Cucumber','Сabbage']
  • Task 7. Create a new array, displaying the values of myCar, myNewCar, and the color of myCar, referenced from both arrays.

let myCar = { color: "green", wheels: 6, engine: { cylinders: 6, size: 2.2 } };
let myNewCar = [myCar, 2, "new", "purchased 2021"];

Solution:

let newCarArr = myNewCar.slice(0, 2);
console.log("myNewCar = " + JSON.stringify(myNewCar));
console.log("newCarArr = " + JSON.stringify(newCarArr));
console.log("myNewCar[0].color = " + myNewCar[0].color);
console.log("newCar[0].color = " + newCarArr[0].color);
  • Task 8. Convert all elements with the ocean class into the array.

<div class="oceanShow">
<div class="ocean"> Pacific Ocean </div>
<div class="ocean"> Atlantic Ocean </div>
<div class="ocean"> Indian Ocean </div>
<div class="ocean"> Southern Ocean </div>
<div class="ocean"> Arctic Ocean </div>
</div>

Solution:

const oceanList = [].slice.call(document.querySelectorAll(".ocean"));
alert(oceanList);