<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Al Amin The Boss</title>
    <description>The latest articles on DEV Community by Al Amin The Boss (@tawhidur876).</description>
    <link>https://dev.to/tawhidur876</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F358310%2F6f2a39a3-ae98-4aed-a62c-2555f66e0545.jpg</url>
      <title>DEV Community: Al Amin The Boss</title>
      <link>https://dev.to/tawhidur876</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/tawhidur876"/>
    <language>en</language>
    <item>
      <title>Javascript Slice method with Example</title>
      <dc:creator>Al Amin The Boss</dc:creator>
      <pubDate>Thu, 19 Sep 2024 16:06:19 +0000</pubDate>
      <link>https://dev.to/tawhidur876/javascript-slice-method-with-example-3o9a</link>
      <guid>https://dev.to/tawhidur876/javascript-slice-method-with-example-3o9a</guid>
      <description>&lt;h2&gt;
  
  
  What is JavaScript Array slice ?
&lt;/h2&gt;

&lt;p&gt;Array.prototype.slice is a JS Array method that is used to extract a contiguous subarray or "slice" from an existing array.&lt;/p&gt;

&lt;p&gt;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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// 

slice();
slice(start);
slice(start, end);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3].slice() // [1,2,3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  Start Index
&lt;/h2&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[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
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3].slice(-1) // [3]
[1,2,3].slice(-2) // [2,3]
[1,2,3].slice(-3) // [1,2,3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  End index
&lt;/h2&gt;

&lt;p&gt;The slice can take a second parameter called the end index.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3].slice(0,3) // [1,2,3]
[1,2,3].slice(0,2) // [1,2]
[1,2,3].slice(0,1) // [1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; n; i++) {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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).&lt;/p&gt;

&lt;p&gt;As in the start index, the end index can be negative as well.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1,2,3].slice(0,-1) // [1,2]
[1,2,3].slice(0,-2) // [1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Kool but what if I want to include the last element?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3].slice(0) // [1,2,3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Yes, simply use the single parameter input.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Use JavaScript slice: Real Example
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;As shown in the examples below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we don't pass any argument to JavaScript slice, we get a shallow copy of the source array with all items:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const allCopied = elements.slice();

// (12) ["Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's effectively [...elements].&lt;/p&gt;

&lt;p&gt;JavaScript Array slice Method with No Second Argument&lt;/p&gt;

&lt;p&gt;If we don't pass the second argument, the extracted JavaScript Array slice extends to the last element:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript Array.prototype.slice with Negative Offsets&lt;/p&gt;

&lt;p&gt;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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const latestTwoBeforeLast = elements.slice(-3, -1);
// (2) ["Make", "Sure"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we pass in a greater value for start than end, we get an empty array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const somewhereWeDontKnow = elements.slice(5, 2); // []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This indicates we have to always start slicing from a lesser positive index.&lt;/p&gt;

&lt;p&gt;Array.prototype.slice: Starting Position Greater Than Length of Array&lt;/p&gt;

&lt;p&gt;Likewise, if we pass in a greater value for start than array's length, we get an empty array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const somewhereInOuterSpace = elements.slice(15, 2); // []
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using JS slice with Sparse Arrays
&lt;/h2&gt;

&lt;p&gt;If our target slice has sparse items, they are also copied over:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const elements = [
  "Please",
  "Send",
  ,
  "Cats",
  ,
  "Monkeys",
  "And",
  "Zebras",
  "In",
  "Large",
  "Cages",
  "Make",
  "Sure",
  "Padlocked",
];

const sparseItems = elements.slice(0, 6);
// (6) [ 'Please', 'Send', &amp;lt;1 empty item&amp;gt;, 'Cats', &amp;lt;1 empty item&amp;gt;, 'Monkeys' ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Array.prototype.slice: Creating Arrays from a List of Arguments
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;The first one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const createArray = (...args) =&amp;gt; Array.prototype.slice.call(args);
const array = createArray(1, 2, 3, 4);
// (4) [1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That was easy.&lt;/p&gt;

&lt;p&gt;The next level way of doing this is in the messiest possible way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const boundSlice = Function.prototype.call.bind(Array.prototype.slice);

const createArray = (...args) =&amp;gt; boundSlice(args);

const array = createArray(1, 2, 3, 4);
// (4) [1, 2, 3, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Slicing a JavaScript String
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript String Slice Nuances
&lt;/h2&gt;

&lt;p&gt;Using JavaScript String slice With No Arguments&lt;/p&gt;

&lt;p&gt;Similar to Array slice, if we don't pass any argument to String slice(), the whole string is copied over:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  JavaScript String slice with Negative Offsets
&lt;/h2&gt;

&lt;p&gt;Similar to Array.prototype.slice, negative values for start and end represent offset positions from the end of the array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
