Home  >  Article  >  Web Front-end  >  Javascript Slice method with Example

Javascript Slice method with Example

Linda Hamilton
Linda HamiltonOriginal
2024-09-20 06:54:08341browse

Javascript Slice method with Example

What is JavaScript Array slice ?

Array.prototype.slice is a JS Array method that is used to extract a contiguous subarray or "slice" from an existing array.

JavaScript slice can take two arguments: the start and the end indicator of the slice -- both of which are optional. It can also be invoked without any argument. So, it has the following call signatures:

// 

slice();
slice(start);
slice(start, end);

If I want to slice the array to take a portion of it, there actually has a built-in function slice for Javascript. Right out of the box, it’ll clone the original array.

[1,2,3].slice() // [1,2,3]

The result points to a new memory address, not the original array. This can be really useful if you want to chain the result with other functions. The real usage is when you provide some input to the slice.

Start Index

The slice can take up to two input parameters. The first one is called the start index, and this would tell where it should start the slice.

[1,2,3].slice(0) // returns [1,2,3]; Original array unmodified
[1,2,3].slice(1) // returns [2,3]; Original array unmodified
[1,2,3].slice(2) // returns [3]; Original array unmodified
[1,2,3].slice(3) // returns []; Original array unmodified

By default, it’ll slice till the end of the array. The interesting thing about the start index is that not only you can use a zero or a positive number, but also you can use a negative number.

[1,2,3].slice(-1) // [3]
[1,2,3].slice(-2) // [2,3]
[1,2,3].slice(-3) // [1,2,3]

When it’s a negative number, it refers to an index counting from the end n . For instance, -1 refers to the last element of the array, -2 refers to the second last element, and etc. Notice there’s no -0 , because there’s no element beyond the last element. This can be quite apparent or confusing depending on the situation.

End index

The slice can take a second parameter called the end index.

[1,2,3].slice(0,3) // [1,2,3]
[1,2,3].slice(0,2) // [1,2]
[1,2,3].slice(0,1) // [1]

The end index, also referred as a range index, points to the element index + 1. What does it mean? To explain this, it would be relatively easier if we can relate to the for statement:

for (let i = 0; i < n; i++) {}

The variable i starts at 0 , the start index; and ends at n, the end index. The end index isn’t the last element of the array, because that would be n - 1 . But when it comes to the end index, n stands for the “end” with the the last element included. If it’s your first time using the end index, just remember how for statement is written, or simply remember taking the last element index and then plus one to it. Another way to think of it is that the end index is open ended, [start, end).

As in the start index, the end index can be negative as well.

1,2,3].slice(0,-1) // [1,2]
[1,2,3].slice(0,-2) // [1]

Pay a bit more attention here. -1 refers to the last element, therefore if used as the second parameter, it means the last element will be excluded, as we have explained, open ended.

Kool but what if I want to include the last element?

[1,2,3].slice(0) // [1,2,3]

Yes, simply use the single parameter input.

How to Use JavaScript slice: Real Example

A typical example of slicing an array involves producing a contiguous section from a source array. For example, the first three items, last three items and some items spanning from a certain index up until another index.

As shown in the examples below:

const elements = [
  "Please",
  "Send",
  "Cats",
  "Monkeys",
  "And",
  "Zebras",
  "In",
  "Large",
  "Cages",
  "Make",
  "Sure",
  "Padlocked",
];

const firstThree = elements.slice(0, 3); // ["Please", "Send", "Cats"]

const lastThree = elements.slice(-3, elements.length); // ["Make", "Sure", "Padlocked"]

const fromThirdToFifth = elements.slice(2, 5); // ["Cats", "Monkeys", "And"]

If we don't pass any argument to JavaScript slice, we get a shallow copy of the source array with all items:

const allCopied = elements.slice();

// (12) ["Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"]

It's effectively [...elements].

JavaScript Array slice Method with No Second Argument

If we don't pass the second argument, the extracted JavaScript Array slice extends to the last element:

const fromThird = elements.slice(2);
// (10) ["Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"]

const lastThree = elements.slice(-3, elements.length);
// (3) ["Make", "Sure", "Padlocked"]

const lastThreeWithNoSecArg = elements.slice(-3);
// (3) ["Make", "Sure", "Padlocked"]

JavaScript Array.prototype.slice with Negative Offsets

Notice also above that, we can pass in negative numbers as arguments. Negative values of the arguments denote offset positions counted backwards from the last item. We can do this for both arguments:

const latestTwoBeforeLast = elements.slice(-3, -1);
// (2) ["Make", "Sure"]

If we pass in a greater value for start than end, we get an empty array:

const somewhereWeDontKnow = elements.slice(5, 2); // []

This indicates we have to always start slicing from a lesser positive index.

Array.prototype.slice: Starting Position Greater Than Length of Array

Likewise, if we pass in a greater value for start than array's length, we get an empty array:

const somewhereInOuterSpace = elements.slice(15, 2); // []

Using JS slice with Sparse Arrays

If our target slice has sparse items, they are also copied over:

const elements = [
  "Please",
  "Send",
  ,
  "Cats",
  ,
  "Monkeys",
  "And",
  "Zebras",
  "In",
  "Large",
  "Cages",
  "Make",
  "Sure",
  "Padlocked",
];

const sparseItems = elements.slice(0, 6);
// (6) [ 'Please', 'Send', <1 empty item>, 'Cats', <1 empty item>, 'Monkeys' ]

Array.prototype.slice: Creating Arrays from a List of Arguments

In this section we go a bit crazy about slicing. We develop two interesting ways with Array.prototype.slice to construct an array from a list of arguments passed to a function.

The first one:

const createArray = (...args) => Array.prototype.slice.call(args);
const array = createArray(1, 2, 3, 4);
// (4) [1, 2, 3, 4]

That was easy.

The next level way of doing this is in the messiest possible way:

const boundSlice = Function.prototype.call.bind(Array.prototype.slice);

const createArray = (...args) => boundSlice(args);

const array = createArray(1, 2, 3, 4);
// (4) [1, 2, 3, 4]

Slicing a JavaScript String

const mnemonic =
  "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked";

const firstThreeChars = mnemonic.slice(0, 3); // "Ple"
const lastThreeChars = mnemonic.slice(-3, mnemonic.length); // "ked"
const fromThirdToFifthChars = mnemonic.slice(2, 5); // "eas"

Again, both arguments represent zero-based index numbers or offset values. Here too, the first argument -- 0 in the firstThree assignment -- stands for the starting index or offset in the source array. And the second argument (3) denotes the index or offset before which extraction should stop.

JavaScript String Slice Nuances

Using JavaScript String slice With No Arguments

Similar to Array slice, if we don't pass any argument to String slice(), the whole string is copied over:

const mnemonic =
  "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked";
const memorizedMnemonic = mnemonic.slice();

// "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"

JavaScript String slice with Negative Offsets

Similar to Array.prototype.slice, negative values for start and end represent offset positions from the end of the array:

const mnemonic =
  "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked";

const lastThreeChars = mnemonic.slice(-3); // "ked"
const latestTwoCharsBeforeLast = mnemonic.slice(-3, -1);  // "ke"

Summary

In this post, we expounded the slice() method in JavaScript. We saw that JavaScript implements slice() in two flavors: one for Arrays with Array.prototype.slice and one for Strings with String.prototype.slice. We found out through examples that both methods produce a copy of the source object and they are used to extract a target contiguous slice from it.

We covered a couple of examples of how function composition and context binding with Function.prototype.call and Function.prototype.bind allows us to define custom functions using Array.prototype.slice to help us generate arrays from a list of arguments.

We also saw that String.prototype.slice is an identical implementation of Array.prototype.slice that removes the overhead of converting a string to an array of characters.

The above is the detailed content of Javascript Slice method with Example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Colour palette GeneratorNext article:Colour palette Generator