JavaScript Array Methods.

In JavaScript, as well as in other programming languages, different methods are used to work with arrays.

Methods simplify the construction of logic and its implementation in a script.

Below are the basic methods for working with arrays in JS.

push

The push() method adds a value to the end of the array.

Let arr = ; arr.push(312); console.log(arr); // →

pop

The pop() method removes the last element from the array or returns its value.

Let arr = ; arr.pop(); console.log(arr); // →

Using the ability to get the value of the last element of an array as an example, we can get the image format:

Let img = "https://example.com/img/name.png"; let format = img.split(".").pop(); console.log(format); // → png console.log(img.split(".")); // → ["https://example", "com/img/name", "png"]

unshift

The unshift() method adds an element to the beginning of the array.

Let arr = ; arr.unshift(312); console.log(arr); // →

shift

The shift() method removes the first element from the array.

Let arr = ; arr.shift(); console.log(arr); // → ;

You need to understand that when using the shift and unshift methods, each element of the array changes its index. This can slow down program execution if the array is large.

split

The split() method is used to transform a string into an array. Split splits a string according to the specified parameter.

Let str = "Anya, Masha, Sasha, Dasha"; // this is a string let arr = str.split(", "); console.log(arr); // → ["Anya", "Masha", "Sasha", "Dasha"] is an array

join

The join() method combines array elements into a string using the delimiter specified in the parameter.

Let arr = ["Notpad++", "Sublime", "VSCode"]; // this is an array let str = arr.join(", "); console.log("Editors for code: " + str); // → "Editors for code: Notpad++, Sublime, VSCode"

slice

The slice() method creates a new array into which it copies elements from the source, starting from the element with the index of the first parameter passed to the method, to the element with the index of the second parameter.

For example: slice(3, 7) will return elements with indexes 3, 4, 5, 6. The element with index 7 will not be included in the array.

If a parameter with a negative value is passed to slice(), then it returns a new array with the number of elements specified in the parameter, but already taken from the end of the original array.

The slice method does not change the original array.

Here are some examples of the slice() method in action:

Let arr = ["A", "B", "C", "D", "E", "F", "G"]; // Returns an array containing elements with indexes from 2 to 5 console.log(arr.slice(2, 5)); // → ["C", "D", "E"] // Returns a new array containing elements with indices from 3 to arr.length console.log(arr.slice(3)); // → ["D", "E", "F", "G"] // Returns a copy of the original array console.log(arr.slice()); // → ["A", "B", "C", "D", "E", "F", "G"] // Returns a new array consisting of the last three elements of the original console.log(arr.slice (-3)); // → ["E", "F", "G"]

splice

The splice() method modifies the contents of an array by removing existing elements and/or adding new ones.

Syntax:

Array.splice(start, deleteCount[, item1[, item2[, ...]]])

Options:

  • start - The index at which to start changing the array. If greater than the length of the array, the real index will be set to the length of the array. If negative, specifies the index of the element from the end.
  • deleteCount - An integer indicating the number of old elements to be deleted from the array. If deleteCount is 0, no elements are deleted. In this case you must specify at least one new element. If deleteCount more quantity elements remaining in the array starting from index start , then all elements up to the end of the array will be removed.
  • itemN - Optional parameters. Elements to be added to the array. If you don't specify any element, splice() will simply remove elements from the array.
Return value Description

If the number of elements specified to be inserted is different from the number of elements to be removed, the array will change length after the call.

Let arr = ["Barca", "Shakhtar", "Manchester United", "Milan", "Real", "Ajax", "Juventus"]; let nax = arr.splice(2, 3); arr.splice(2, 3); console.log(nax); // → ["Manchester United", "Milan", "Real"] console.log(arr); // → ["Barca", "Shakhtar"] arr.splice(1, 0, "Zenit", "CSKA", "Spartak"); console.log(arr); // → [Barça, Zenit, CSKA, Spartak, Shakhtar]

reverse

The reverse() method reverses the order of the array elements. As a result, the first element of the array becomes the last, and the last element becomes the first.

Let arr = ; console.log(arr.reverse()); // → console.log(["Alice", "BG", "GO", "DDT"].reverce()); // → ["DDT", "GO", "BG", "Alice"]

map

The map() method iterates through the elements of the array, producing specified actions and returns a copy of the array with the changed elements.

In the example below, to each array element we add the index value of this element (7 + 0, 2 + 1, 15 + 2, 4 + 3, 31 + 4):

Let arr = ; let testMap = arr.map((element, index) => element + index); console.log(testMap); //

or multiply each value of the array, for example, by 12

Let arr = ; let testMap = arr.map(a => a * 12); console.log(testMap); // →

filter

The filter() method is used to filter arrays. It iterates through the array, returning only those elements that pass a given condition.

For example, let's filter the values ​​of an array of numbers, leaving only those that are greater than 21

Let arr = ; let testFilter = arr.filter(element => element > 21); console.log(testFilter); // →

Please note that 21 was not included in the array result, since the condition was to return something that is greater than 21. In order for 21 to be included in the array, we set the condition as greater than or equal to: element >= 21

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 ​​are 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

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.

The splice() method in Javascript arrays modifies the contents of the array by adding new elements and 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
Computer