Skip to content
Advertisements

Array slice()

JavaScript Array slice() Definition

The Slice() method copies the desired portion of a directory.

Syntax:

array.slice(start, end)

start: Slice the array starting from an element index
end: Slice the array until another element index


        let list = ["zero", "first", "second", "third"];
        let newList1 = list.slice(0, 2);
        let newList2 = list.slice(2, 4);
        console.log("original list: " + list);
        console.log("new list 1: " + newList1);
        console.log("new list 2: " + newList2)

original list: zero,first,second,third
new list 1: zero,first
new list 2: second,third

This defines the copied section as a new array. So this array is independent in the copied sequence. The change in any one does not change the other. (The original array will not change)

        let list = ["zero", "first", "second", "third"];
        let newList = list.slice(1, 3);

        list.push("forth");
        
        console.log(list);
        console.log(newList);

[“zero”, “first”, “second”, “third”, “forth”]
[“first”, “second”]

Note: The slice () method does not include the last element in the values ​​to be given for copying.

        let list = ["zero", "first", "second", "third"];
        let newList1 = list.slice(0, 1);
        let newList2 = list.slice(0, 2);
        let newList3 = list.slice(0, 3);
        let newList4 = list.slice(0, 4);
        
        console.log(list);
        console.log(newList1); // first not included
        console.log(newList2); // second not included
        console.log(newList3); // third not included
        console.log(newList4); 

[“zero”, “first”, “second”, “third”]
[“zero”]
[“zero”, “first”]
[“zero”, “first”, “second”]
[“zero”, “first”, “second”, “third”]


JavaScript Array slice() Example

Example 1

        let animals = ["dog", "cat", "donkey", "monkey"];
        let copyAnimals = animals.slice(-4, -1)
        
        console.log("animals: " + animals);
        console.log("copy animals: " + copyAnimals);

output:

animals: dog,cat,donkey,monkey
copy animals: dog,cat,donkey


Example 2

        let list = [1,2,3,"truecodes.org",true];
        let copylist = list.slice(2, 4)
        
        console.log("animals: " + list);
        console.log("copy copylist: " + copylist);

output:

animals: 1,2,3,truecodes.org,true
copy copylist: 2,3,truecodes.org


Example 3

if the last value is not entered, it takes the last element.

        var list = ["zero","first","second","third"]
        console.log(list.slice(2));

output:

[“second”, “third”]


Example 4

        var list = ["zero","first","second","third"]
        console.log(list.slice(-2));

output:

[“second”, “third”]


Streamlining cross-browser behavior

/**
 * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
 * on host objects like NamedNodeMap, NodeList, and HTMLCollection
 * (technically, since host objects have been implementation-dependent,
 * at least before ES2015, IE hasn't needed to work this way).
 * Also works on strings, fixes IE < 9 to allow an explicit undefined
 * for the 2nd argument (as in Firefox), and prevents errors when
 * called on other DOM objects.
 */
(function () {
  'use strict';
  var _slice = Array.prototype.slice;

  try {
    // Can't be used with DOM elements in IE < 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE < 9
    // This will work for genuine arrays, array-like objects, 
    // NamedNodeMap (attributes, entities, notations),
    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
    Array.prototype.slice = function(begin, end) {
      // IE < 9 gets unhappy with an undefined end argument
      end = (typeof end !== 'undefined') ? end : this.length;

      // For native Array objects, we use the native slice function
      if (Object.prototype.toString.call(this) === '[object Array]'){
        return _slice.call(this, begin, end); 
      }

      // For array like object we handle it ourselves.
      var i, cloned = [],
        size, len = this.length;

      // Handle negative value for "begin"
      var start = begin || 0;
      start = (start >= 0) ? start : Math.max(0, len + start);

      // Handle negative value for "end"
      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
      if (end < 0) {
        upTo = len + end;
      }

      // Actual expected size of the slice
      size = upTo - start;

      if (size > 0) {
        cloned = new Array(size);
        if (this.charAt) {
          for (i = 0; i < size; i++) {
            cloned[i] = this.charAt(start + i);
          }
        } else {
          for (i = 0; i < size; i++) {
            cloned[i] = this[start + i];
          }
        }
      }

      return cloned;
    };
  }
}());

Source of this code: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


Browser Support

Chrome1
Edgeyes
Firefox1
Internet Exploreryes
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes
Advertisements

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: