JavaScript Array Methods. Slice - cutting and creating

💖 Do you like it? Share the link with your friends

Arrays can be manipulated through various methods provided by the Array constructor.

Pop/push and shift/unshift methods

Let's look at the pop() and push() methods. These methods allow you to work with arrays as if they were stacks. A stack is a data structure in which access to elements is organized according to the LIFO principle (English: last in - first out, “last in - first out”). The principle of operation of the stack can be compared to a stack of plates: to take the second one from the top, you need to remove the top one. How it works is shown in the figure:

And so let's get back to looking at the push() and pop() methods. The push() method adds one or more new elements to the end of the array and returns its new length. pop() method - removes the last element of the array, reduces the length of the array and returns the value it removed. It's worth noting that both of these methods modify the array in place, rather than creating a modified copy of it.

Var foo = ; // foo: foo.push(1,2); // foo: Returns 2 foo.pop(); // foo: Returns 2 foo.push(3); // foo: Returns 2 foo.pop(); // foo: Returns 3 foo.push(); // foo: ] Returns 2 foo.pop() // foo: Returns foo.pop(); // foo: Returns 1 var fruits = ["pears", "bananas", "apples"]; var picked = fruits.pop(); document.write("You picked my " + picked); Try »

The shift() and unshift() methods behave much the same as pop() and push(), except that they insert and remove elements at the beginning of the array. The unshift() method shifts existing elements to larger indices to make room for new elements, adds one or more elements to the beginning of the array, and returns the new length of the array. The shift() method removes the first element of an array and returns its value, shifting all subsequent elements to occupy the free space at the beginning of the array.

Var f = ; // f: f.unshift(1); // f: Returns: 1 f.unshift(22); // f: Returns: 2 f.shift(); // f: Returns: 22 f.unshift(3,); // f:,1] Returns: 3 f.shift(); // f:[,1] Returns: 3 f.shift(); // f: Returns: f.shift(); // f: Returns: 1

join method

The Array.join() method is used to join the elements of an array into one string. The method can be passed an optional string argument, which will be used to separate elements in the string. If the delimiter is not specified, the default delimiter character when calling the method will be a comma.

Var a = ["Wind","Rain","Fire"]; var myVar1 = a.join(); //"Wind,Rain,Fire" var myVar2 = a.join(", "); //"Wind, Rain, Fire" var myVar3 = a.join(" + "); //"Wind + Rain + Fire" document.write(myVar1 + "
" + myVar2 + "
" + myVar3); Try "

The Array.join() method is the inverse of the String.split() method, which creates an array by splitting a string into fragments.

reverse method

The Array.reverse() method reverses the order of elements in an array and returns an array with the elements rearranged. This method does not create a new array with reordered elements, but rather reorders them in an existing array.

Var myArr = ["one", "two", "three"]; document.write(myArr.reverse()); Try »

concat method

The Array.concat() method creates and returns a new array containing the elements of the original array on which concat() was called, sequentially augmented with the values ​​of all arguments passed to concat(). If any of these arguments is itself an array, then all its elements will be added. The names of the arrays are used as arguments and are specified in the order in which their elements are to be combined.

Var a = ; a.concat(4, 5) //Returns a.concat(); //same thing - returns a.concat(,) //Returns

sort method

The Array.sort() method sorts the array elements in place and returns the sorted array. If the sort() method is called without an argument, it sorts the array elements in alphabetical order (temporarily converting them to strings to perform the comparison). The sort() method can take a comparison function as an argument, which determines the sort order of the elements.

Var a = ["Kiwi", "Oranges", "Pears"]; a.sort(); var s = a.join(", "); //Oranges, Pears, Kiwi document.write(s); //example with numbers var myArr = ; myArr.sort(); document.write(myArr); //1,10,2 Try »

You probably expected to see a slightly different result from sorting numbers. This sorting occurs because the sort() method sorts elements by converting them into strings. Therefore, their order turns out to be string - after all, “10”

To sort in order other than alphabetical, you can pass a comparison function as an argument to the sort() method. However, it should be taken into account that you will have to write the comparison function yourself. This function must have two parameters because it sets which of its two arguments should appear first in the sorted list. To make it easier to understand and write such a function, there are several rules by which the order of elements will be determined:

  • If the first argument must come before the second, the comparison function returns a negative number (if a
  • If the first argument must follow the second, then the comparison function returns positive number(if a > b)
  • If two values ​​are equivalent (i.e. their order is not important), the comparison function returns 0 (if a == b)

For comparison, the function uses array elements as its arguments:

Function foo(a,b) ( //define the check function if (a b) return 1; return 0; //if a == b ) var a = ; a.sort(foo); //only the function name is passed as an argument document.write(a.join(", ")); //write the same thing more briefly var a = ; a.sort(function(a,b) ( //use anonymous function return a - b; //function returns value 0 )); document.write(a); //1,2,5,10 Try »

The first entry in the example is written this way to make it easier to understand how it works. Notice how convenient it is to use an anonymous function in the second fragment. It is called only once, so there is no need to give it a name.

Note: If there are undefined elements in the array, they are moved to the end of the array.

slice method

The Array.slice() method is used to copy a specified section from an array and returns a new array containing the copied elements. The original array does not change.

Method syntax:

ArrayName.slice(begin, end);

Array_name should be replaced with the name of the array from which you want to extract a specific set of elements for the new array. The method takes two arguments that specify the beginning and end of the returned array. The method copies a section of the array, starting from begin to end, not including end. If only one argument is given, the returned array will contain all elements from the specified position to the end of the array. You can use negative indices - they are counted from the end of the array.

Var arr = ; arr.slice(0,3); //Returns arr.slice(3); //Returns arr.slice(1,-1); //Returns arr.slice(-3,-2); //Returns

splice method

The Array.splice() method is a universal method for working with arrays. It modifies the array in place rather than returning a new modified array like the slice() and concat() methods do. The splice method can remove elements from an array, insert new elements, replace elements - one at a time and simultaneously. It returns an array consisting of the removed elements, if no element was removed it will return an empty array.

Method syntax:

Array_name.splice(index, quantity, elem1, ..., elemN);

The first argument specifies the index in the array at which to begin inserting or removing elements. The second argument specifies the number of elements that should be removed from the array starting from the index specified in the first argument; if the second argument is 0, then no elements will be removed. If the second argument is omitted, all array elements from the specified index to the end of the array are removed. When using a negative position number, elements will be counted from the end of the array.

Var fruits = ["oranges", "apples", "pears", "grapes"]; var deleted = fruits.splice(2,2); //returns ["pears", "grapes"] document.write(deleted); var arr = ; arr.splice(4); //Returns ; the array became: arr.splice(1,2); //Returns ; the array became: arr.splice(1,1); //Returns ; array became: Try »

The first two arguments to the splice() method specify the array elements to be removed. These two arguments can be followed by any number of additional arguments specifying the elements to be inserted into the array, starting at the position specified by the first argument.

Var fruits = ["oranges", "apples"]; fruits.splice(2,0, "watermelons"); //returns document.write(fruits); //became ["oranges", "apples", "watermelons"] var arr = ; arr.splice(2,0,"a","b"); //Returns ; became arr.splice(2,2,); //Returns ["a","b"]; became ,3,4,5] Try »

It is worth noting that, unlike concat(), the splice() method does not split the arrays passed as arguments into individual elements. That is, if the method is passed an array to insert, it inserts the array itself, and not the elements of that array.

toString method

The toString() method converts the elements of an array into a string using a comma as the delimiter character.

Var arr = ["Milk","Bread","Cookies"]; var food = arr.toString(); document.write(food); //Milk,Bread,Cookies Try »

Note that the method returns the same string as join() when called without arguments.

indexOf and lastIndexOf

The indexOf method returns the index of an element whose value is equal to the value passed as an argument to the method.

Syntax of the indexOf() and lastIndexOf() methods:

Array_name.indexOf(search_element, index) array_name.lastIndexOf(search_element, index)

The first argument of the method specifies the value of the element whose index needs to be found, the second argument (optional) specifies the index from which the search will begin. If there are several identical occurrences, the smallest (first) index is selected. If an element with the desired value is not found, the method will return -1. Inside the method, strict comparison (===) is used for searching.

Var a = ; a.indexOf(3); //return 2 a.indexOf(3,4); //return 6 a.indexOf(35); //return -1: there is no element with this value a.indexOf(2); // 1

The lastIndexOf() method also returns the index of the element, the value of which is equal to the value passed to the method as an argument. The only difference is that the lastIndexOf() method selects the largest (last) index.

Var a = ; a.lastIndexOf(3); //return 7 a.lastIndexOf(35); //return -1: there is no element with this value a.lastIndexOf(2); // 6

Iterator methods

The methods described below are iterators. All modern browsers have methods for working with arrays that are designed to iterate over elements and perform various actions on them. These methods are forEach(), map(), filter(), every(), some, reduce() and reduceRight().

They iterate over the elements of the array starting from 0 to length - 1 and, if the element exists, pass it to the callback handler function.

forEach

Method syntax:

ArrayName.forEach(callback, thisArg)

The first argument specifies the callback function that the forEach() method will call for each element of the array. You need to write the implementation of the called handler function yourself. The called function must have three parameters: the first parameter takes as an argument the value of the array element, the second - the index of the element, and the third - the array itself. However, if you only need to use the values ​​of the array elements, you can write a function with only one parameter. The second argument - thisArg (optional) will be passed as the value of this.

Var arr = ; function foo(value) ( ​​var sum = value * this; return document.write(sum + "
"); ) arr.forEach(foo, 5); //the second argument will be passed as the value of this //example with three parameters var a = ; a.forEach(function(el, idx, a) ( document.write( "a["+idx+"] = "+el+" in ["+a+"]
"); )); Try »

filter

Method syntax:

Array_name.filter(callback, thisObject)

The filter() method creates and returns a new array that will contain only those array elements for which the callback function returns true.

Function isBig(element, index, array) ( //returns numbers that are greater than or equal to 10 return (element >= 10); //if the value of the element is greater than or equal to 10, the expression will return true ) var filtered = .filter(isBig) ; //filtered

map

The map() method creates and returns a new array, which will consist of the results of calling the callback(item, idx, ar) function for each element of the array.

Var a = ; var b = a.map(function(item, idx, arr) ( return item * item; )); // b =

every and some

The every() method returns true if, for all elements of the array, the specified function used to check them returns true.

The some() method returns true if one or more elements in the specified function return true during testing.

Var a = ; a.every(function(x) ( return x 10; )) //true: one number > 10

reduce and reduceRight

Method syntax:

array_name.reduce(callback, initialValue) array_name.reduceRight(callback, initialValue)

The reduce() method applies the specified callback function to two values ​​in the array at once, iterating through the elements from left to right, while storing the intermediate result.

callback function arguments: (previousValue, currentItem, index, array)

  • previousValue - the returned result of the callback function (also known as the intermediate result)
  • currentItem - current element of the array (elements are sorted in order from left to right)
  • index - index of the current element
  • array - processed array

initialValue is the object used as the first argument of the first call to the callback function. Simply put, the value of previousValue when first called is equal to initialValue. If there is no initialValue, then it is equal to the first element of the array, and the search starts from the second:

Var a = ; function foo(prevNum,curNum) ( sum = prevNum + curNum; alert(sum); return sum; ) var result = a.reduce(foo, 0); document.write(result); Try »

Let's look at how this example works. The first arguments to the function foo are:

  • prevNum = 0 (since initialValue is 0)
  • curNum = 1 (current element is the 1st element of the array)

1 is added to the number 0. This result (sum: 1) will be passed as prevNum the next time the function is run. And so on until it reaches the last element. The returned result, the sum from the last run, will be 15 (1+2+3+4+5).

The reduceRight method works similarly to the reduce method, but it goes through the array from right to left:

Var a = ["h","o","m","e"]; function bar(prevStr, curItem) ( return prevStr + curItem; ) document.write(a.reduceRight(bar)); //emoh

Definition and Application

The JavaScript splice() method allows you to change the contents of an array by removing existing elements and/or adding new elements to the array.

Please note that the splice() method modifies an existing array and does not return a new one. The removed elements are returned as a new Array object.

Browser support Method
Opera
IExplorer
Edge
splice()YesYesYesYesYesYes
JavaScript syntax: // only with index indication array.splice( start) // indicating the index and number of elements to be removed array.splice( start, deleteCount) // indicating the index, the number of elements to be removed and elements to be added array.splice( start, deleteCount, element1, element2, ..., elementX) JavaScript version ECMAScript 3 (implemented in JavaScript 1.2) Parameter values Parameter Description
start An integer that specifies the index of the array from which elements will be removed from the array and/or added to the array. Negative values ​​are allowed, in this case the index from which the method will be called will be calculated using the following formula: length (array length) + start. Is a required value.
deleteCount An integer that specifies the number of elements to be removed from the array, starting from the index specified in start. If deleteCount is 0, then elements are not removed. If the value deleteCount is greater than the number of remaining elements in the array, then all remaining elements of the array will be deleted. Optional value negative values not allowed .
element(-s) The element or elements that will be added to the array. The index of the array at which new elements will be inserted corresponds to the parameter start. Optional value.
Example of using var x = ; // initialize a variable containing the array x.splice(3 ); x.splice(-3 ); // variable value x.splice(2 , 2 ); // variable value x.splice(-2 , 2 ); // variable value x.splice(0 , 2 , "z ", true ); // variable value ["z", true, 3, "a", "b", "c"] x.splice(3, 0, "z", "z", "z"); // variable value The splice() method in Javascript arrays changes the contents of the array, adding new elements, removing old ones. Syntax

Its syntax is as follows:

Array.splice(index, howMany, [, ..., elementN]);

Parameter details
  • index – The index at which the array begins to change.
  • howMany – An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
  • element1, ..., elementN – Elements added to the array. If you don't specify any elements, splice simply removes elements from the array.
Return value

Returns the extracted array based on the passed parameters.

Example

Try the following example.

JavaScript - Arrays. Method splice var arr = ["orange", "melon", "milk", "sugar", "coffee"]; var removed = arr.splice(2, 0, "water"); document.write("After adding 1: " + arr); document.write("
removed: " + removed); removed = arr.splice(3, 1); document.write("
After adding 1: " + arr); document.write("
removed: " + removed);

Output After adding 1: orange,melon,water,milk,sugar,coffee removed: After adding 1: orange,melon,water,sugar,coffee removed: milk

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place .

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax let arrDeletedItems = array .splice(start [, deleteCount [, item1 [, item2 [, ...]]]]) Parameters start The index at which to start changing the array. If greater than the length of the array, start will be set to the length of the array. If negative, it will begin that many elements from the end of the array. (In this case, the origin -1 , meaning - n is the index of the n th last element, and is therefore equivalent to the index of array .length - n .) If array .length + start is less than 0 , it will begin from index 0 . deleteCount Optional An integer indicating the number of elements in the array to remove from start . If deleteCount is omitted, or if its value is equal to or larger than array .length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.

Note: In IE8, it won't delete all when deleteCount is omitted.

If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below). item1 , item2 , ... Optional The elements to add to the array, beginning from start . If you do not specify any elements, splice() will only remove elements from the array.

Return value

An array containing the deleted elements.

If only one element is removed, an array of one element is returned.

If no elements are removed, an empty array is returned.

Description

If the specified number of elements to insert differs from the number of elements being removed, the array"s length will be different at the end of the call.

Examples Remove 0 (zero) elements from index 2, and insert "drum" let myFish = ["angel", "clown", "mandarin", "sturgeon"] let removed = myFish.splice(2, 0, "drum" ) // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed is , no elements removed Remove 0 (zero) elements from index 2, and insert "drum" and "guitar" let myFish = ["angel", "clown", "mandarin", "sturgeon"] let removed = myFish.splice(2, 0, "drum", "guitar") // myFish is ["angel" , "clown", "drum", "guitar", "mandarin", "sturgeon"] // removed is , no elements removed Remove 1 element from index 3 let myFish = ["angel", "clown", "drum" , "mandarin", "sturgeon"] let removed = myFish.splice(3, 1) // removed is ["mandarin"] // myFish is ["angel", "clown", "drum", "sturgeon"] Remove 1 element from index 2, and insert "trumpet" let myFish = ["angel", "clown", "drum", "sturgeon"] let removed = myFish.splice(2, 1, "trumpet") // myFish is ["angel", "clown", "trumpet", "sturgeon"] // removed is ["drum"] Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue" let myFish = ["angel", "clown", "trumpet", "sturgeon"] let removed = myFish.splice(0, 2, "parrot", "anemone", "blue") // myFish is ["parrot", " anemone", "blue", "trumpet", "sturgeon"] // removed is ["angel", "clown"] Remove 2 elements from index 2 let myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"] let removed = myFish.splice(2, 2) // myFish is ["parrot", "anemone", "sturgeon"] // removed is ["blue", "trumpet"] Remove 1 element from index -2 let myFish = ["angel", "clown", "mandarin", "sturgeon"] let removed = myFish.splice(-2, 1) // myFish is ["angel", "clown" , "sturgeon"] // removed is ["mandarin"] Remove all elements after index 2 (incl.) let myFish = ["angel", "clown", "mandarin", "sturgeon"] let removed = myFish.splice (2) // myFish is ["angel", "clown"] // removed is ["mandarin", "sturgeon"] Specifications Specification Status Comment
ECMAScript Latest Draft (ECMA-262)
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Array.prototype.splice" in that specification.
Standard
ECMAScript 5.1 (ECMA-262)
The definition of "Array.prototype.splice" in that specification.
Standard
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.jssplice
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5

Notes

Full support 5.5

Notes

Notes From Internet Explorer 5.5 through 8, all elements of the array will not be deleted if deleteCount is omitted. This behavior was fixed in Internet Explorer 9.
Opera Full support YesSafari Full support 1WebView Android Full support YesChrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support Yesnodejs Full support Yes
Legend Full support Full support See implementation notes. See implementation notes.

All the benefits of built-in JavaScript methods can only be appreciated by properly understanding how they work. In this article, we will look at three methods: slice(), splice() and split(). Even experienced developers often confuse them, perhaps because all three names are so similar.

Students and aspiring developers: read this article carefully - you may be asked about these three methods during an interview.

At the end you will find a summary of information about all three methods. Let's start.

Arrays in JavaScript

First you need to understand how JavaScript arrays work. As in other programming languages, arrays are used to store multiple units of data. The difference is that JavaScript arrays can contain multiple types of data at the same time.

To work with such arrays, we need JavaScript methods: for example, slice() & splice(). You can create an array like this:

Let arrayDefinition = ; // Array declaration in JS

Now let's create another array with different types of data:

Let array = ;

In JavaScript you can create arrays with different types data: with numbers, strings and logical values.

Slice()

The slice() method copies a given portion of an array and returns that copied portion as a new array. The original array does not change.

Array.slice(from, until);

  • From: Slices the array starting from this element
  • Until: Slices the array down to this element

For example, I want to slice the first three elements from the array mentioned above. The first element of an array is always designated 0, so the from parameter is 0.

Array --> 1 // included array --> 2 // included array --> 3 // included array --> "hello world" // not included

This is where things can get confusing! That's why I declared “until” .

Let newArray = array.slice(0, 3); // Return value is also an array

Finally I create a new array and bind it to the newArray variable. Let's see the result:

Slicing an array and adding elements to a new array


The newArray variable becomes a new array, the original array remains unchanged.

Important note: The Slice() method can also be used on strings.

Splice()

The name of this method is similar to slice(): developers often get confused with such similar names. The splice() method adds and removes elements from an array, changing it. Let's see how to add and remove elements using the splice() method:

Removing items

To remove elements, enter the element to start with (index) and the number of elements to remove (number of elements):

Array.splice(index, number of elements);

The Index parameter is the starting point for removing elements. Elements with a sequence number less than the specified Index parameter will not be deleted:

Array.splice(2); // Every element starting from index 2, will be removed

If you do not specify the second parameter, all elements from the specified Index parameter to the end will be removed:

As another example, I specified 1 as the second parameter: this way, each time the splice() method is repeated, it will remove one element at a time, starting with the second one:

Array.splice(2, 1);

Array before splice() method

Splice() is applied once:

Element 3 is removed: therefore, the “hello world” element now has index number 2

Splice() is applied twice:

This time, the “hello world” element was removed because its ordinal number is 2

This can be continued until there are no elements left with serial number 2.

Adding elements

To add elements using splice(), you need to enter them as the third, fourth, and fifth element (depending on how many elements you need to add):

Array.splice(index, number of elements, element, element);

As an example, let's add elements a and b to the very beginning of the array:

Array.splice(0, 0, "a", "b");


Elements a and b are added to the beginning of the array

Split()

The Slice() and splice() methods are used for arrays. The split() method is used for strings. It splits a string into substrings and returns them as an array. This method has 2 parameters, both of which are optional.

String.split(separator, limit);

  • Separator: determines how the string will be divided into substrings: comma, sign, etc.
  • Limit: limits the number of substrings to a given number

The split() method does not work directly with arrays. However, you can first convert the array elements to strings and then use the split() method.

Let's see how it works.

First, we convert the array to a string using the toString() method:

Let myString = array.toString();

Then we split the string myString with commas and limit the number of substrings to three. Then we convert the strings into an array:

Let newArray = myString.split(",", 3);

The first 3 elements were returned as an array

Thus, the elements of the myString array are separated by commas. We set a limit of 3 substrings, so the first 3 elements were returned as an array.

Note: Using the command array.split(""); You can divide all the characters in a string into substrings.


All characters are divided into substrings

Abstract: Slice()
  • Copies elements from an array
  • Returns them to a new array
  • Does not change the original array
  • Slices an array using the from and until parameters: array.slice (from, until)
  • Does not include the parameter specified in “until”
  • Used in both arrays and strings
Splice()
  • Adds and removes elements from an array
  • Returns an array of removed elements
  • Changes the array
  • Adding elements: array.splice (index, number of elements, element)
  • Removing elements: array.splice (index, number of elements)
  • Only used in arrays
Split()
  • Divides strings into substrings
  • Returns them as an array
  • 2 parameters, both of which are optional: string.split(separator, limit)
  • Doesn't change the original string
  • Only used in strings

JavaScript has many other built-in methods for working with arrays and strings. Once you learn how to use them, programming will become much easier.



tell friends