Computer literacy, assistance and repair

Push javascript examples. Arrays

Arrays

An array is an ordered collection of values. The values ​​in an array are called elements, and each element is characterized by a numeric position in the array, called an index. Arrays in JavaScript are untyped: elements of an array can be of any type, and different elements of the same array can have different types. Array elements can even be objects or other arrays, allowing you to create complex data structures such as arrays of objects and arrays of arrays.

JavaScript array indexes start at zero and use 32-bit integers - the first element of the array has index 0. JavaScript arrays are dynamic: they can grow and shrink in size as needed; there is no need to declare fixed array sizes when creating them, or to re-allocate memory when their sizes change.

Arrays in JavaScript are a specialized form of objects, and array indices mean little more than just property names, which coincidentally are integers.

Creating Arrays

The easiest way to create an array is to use a literal, which is a simple comma-separated list of array elements surrounded by square brackets. The values ​​in an array literal do not have to be constants - they can be any expressions, including object literals:

Var empty = ; // Empty array var numbers = ; // Array with five numeric elements var misc = [ 1.1, true, "a", ]; // 3 elements of different types + trailing comma var base = 1024; var table = ; // Array with variables var arrObj = [, ]; // 2 arrays inside containing objects

Array literal syntax allows you to insert an optional trailing comma, i.e. the literal [,] matches an array with two elements, not three.

Another way to create an array is to call the Array() constructor. You can call the constructor in three different ways:

    Call the constructor without arguments:

    Var arr = new Array();

    In this case, an empty array will be created, equivalent to the literal.

    Call the constructor with a single numeric argument specifying the length of the array:

    Var arr = new Array(10);

    In this case, an empty array of the specified length will be created. This form of calling the Array() constructor can be used to pre-allocate memory for an array if the number of its elements is known in advance. Note that this does not store any values ​​in the array.

    Explicitly specify the values ​​of the first two or more array elements or one non-numeric element in the constructor call:

    Var arr = new Array(5, 4, 3, 2, 1, "test");

    In this case, the arguments to the constructor become the values ​​of the elements of the new array. Using array literals is almost always easier than using the Array() constructor.

Reading and Writing Array Elements

Array elements are accessed using the operator. To the left of the brackets there must be an array reference. Inside the parentheses there must be an arbitrary expression that returns a non-negative integer value. This syntax is useful for both reading and writing the value of an array element. Therefore, all of the following JavaScript instructions are valid:

// Create an array with one element var arr = ["world"]; // Read element 0 var value = arr; // Write the value to element 1 arr = 3.14; // Write the value to element 2 i = 2; arr[i] = 3; // Write the value to element 3 arr = "hello"; // Read elements 0 and 2, write the value to element 3 arr] = arr;

Let me remind you that arrays are a specialized type of object. Square brackets used to access array elements act exactly the same as square brackets used to access object properties. The JavaScript interpreter converts the numeric indexes in parentheses into strings—index 1 becomes the string "1"—and then uses the strings as property names.

There's nothing special about converting numeric indexes to strings: you can do the same with regular objects:

Var obj = (); // Create a simple object obj = "one"; // Index it with integers

The thing about arrays is that when you use property names that are non-negative integers, arrays automatically determine the value of the length property. For example, above we created an array arr with a single element. It then assigned values ​​to its elements at indexes 1, 2, and 3. As a result of these operations, the value of the array's length property changed to 4.

You should clearly distinguish indexes in an array from object property names. All indices are property names, but only properties with names represented by integers are indices. All arrays are objects, and you can add properties to them with any names. However, if you touch properties that are array indices, arrays respond by updating the value of the length property as necessary.

Please note that negative and non-integer numbers can be used as array indices. In this case, numbers are converted to strings, which are used as property names.

Adding and Removing Array Elements

We've already seen that the easiest way to add elements to an array is to assign values ​​to new indices. You can also use the push() method to add one or more elements to the end of an array:

Var arr = ; // Create an empty array arr.push("zero"); // Add a value to the end arr.push("one",2); // Add two more values

You can also add an element to the end of the array by assigning a value to the arr element. The unshift() method can be used to insert an element at the beginning of an array, which shifts existing elements in the array to higher index positions.

You can delete array elements using the delete operator, just like regular object properties:

Var arr = ; delete arr; 2 in arr; // false, index 2 in the array is not defined arr.length; // 3: the delete operator does not change the length property of the array

Removing an element is similar (but slightly different) to assigning the value undefined to that element. Note that applying the delete operator to an array element does not change the value of the length property or shift down elements with higher indexes to fill the void left by deleting the element.

It is also possible to remove elements at the end of an array by simply assigning a new value to the length property. Arrays have a pop() method (the opposite of push()), which reduces the length of the array by 1 and returns the value of the removed element. There is also a shift() method (the opposite of unshift()), which removes the element at the beginning of the array. Unlike the delete operator, the shift() method shifts all elements down to a position below their current index.

Finally, there is a multi-purpose splice() method that allows you to insert, remove, and replace elements of arrays. It changes the value of the length property and shifts array elements to lower or higher indexes as needed. We will look at all these methods a little later.

Multidimensional arrays

JavaScript doesn't support "true" multidimensional arrays, but it does provide a good way to simulate them using arrays of arrays. To access a data element in an array of arrays, simply use the operator twice.

For example, suppose the variable matrix is ​​an array of arrays of numbers. Each element of matrix[x] is an array of numbers. To access a specific number in an array, you can use the expression matrix[x][y]. Below is a specific example where a two-dimensional array is used as a multiplication table:

// Create a multidimensional array var table = new Array(10); // There are 10 rows in the table for(var i = 0; i

Methods of the Array class

The ECMAScript 3 standard defines Array.prototype as a set of convenient functions for working with arrays, which are available as methods on any array. These methods will be presented in the following subsections.

join() method

The Array.join() method converts all array elements into strings, joins them, and returns the resulting string. As an optional argument, you can pass a string to the method that will be used to separate the elements in the result string. If a delimiter string is not specified, a comma is used. For example, the following fragment results in the string "1,2,3":

Var arr = ; arr.join(); // "1,2,3" arr.join("-"); // "1-2-3"

reverse() method

The Array.reverse() method reverses the order of elements in an array and returns a reordered array. The permutation is performed directly in the original array, i.e. This method does not create a new array with the reordered elements, but rather reorders them in an already existing array. For example, the following snippet, using the reverse() and join() methods, results in the string "3,2,1":

Var arr = ; arr.reverse().join(); // "3,2,1"

sort() method

The Array.sort() method sorts the elements in the source array and returns the sorted array. If the sort() method is called without arguments, the sorting is done in alphabetical order (elements are temporarily converted to strings for comparison if necessary). Undefined elements are moved to the end of the array.

To sort in order other than alphabetical, you can pass a comparison function as an argument to the sort() method. This function sets which of its two arguments should come first in the sorted list. If the first argument must come before the second, the comparison function must return a negative number. If the first argument is to follow the second in a sorted array, then the function must return a number greater than zero. And if two values ​​are equivalent (that is, their order does not matter), the comparison function should return 0:

Var arr = ; arr.sort(); // Alphabetical order: 1111, 222, 33, 4 arr.sort(function(a,b) ( // Numeric order: 4, 33, 222, 1111 return a-b; // Returns 0 // depending on the sort order a and b)); // Sort in the opposite direction, from largest to smallest arr.sort(function(a,b) (return b-a));

Notice how convenient it is to use an unnamed function in this snippet. The comparison function is only used here, so there is no need to give it a name.

concat() method

The Array.concat() method creates and returns a new array containing the elements of the original array on which concat() was called and the values ​​of any arguments passed to concat(). If any of these arguments is itself an array, its elements are added to the returned array. It should be noted, however, that there is no recursive transformation of an array of arrays into a one-dimensional array. The concat() method does not change the original array. Below are some examples:

Var arr = ; arr.concat(4, 5); // Return arr.concat(); // Return arr.concat(,) // Return arr.concat(4, ]) // Return ]

slice() method

The Array.slice() method returns a slice, or subarray, of the specified array. The two method arguments specify the start and end of the returned fragment. The returned array contains the element whose number is specified in the first argument, plus all subsequent elements, up to (but not including) the element whose number is specified in the second argument.

If only one argument is given, the returned array contains all elements from the starting position to the end of the array. If any of the arguments is negative, it determines the element number relative to the end of the array. So, argument -1 corresponds to the last element of the array, and argument -3 corresponds to the third element of the array from the end. Here are some examples:

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

splice() method

The Array.splice() method is a generic method that performs insertion or deletion of array elements. Unlike the slice() and concat() methods, the splice() method modifies the original array on which it was called. Note that the splice() and slice() methods have very similar names, but perform completely different operations.

The splice() method can remove elements from an array, insert new elements, or do both at the same time. Array elements are shifted as necessary to create a continuous sequence after insertion or deletion.

The first argument of the splice() method specifies the position in the array from which insertion and/or deletion will be performed. The second argument specifies the number of elements that should be removed (cut) from the array. If the second argument is omitted, all array elements from the specified to the end of the array are removed. The splice() method returns an array of the removed elements or (if no elements were removed) an empty array.

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

Var arr = ; arr.splice(4); // Return , arr = arr.splice(1,2); // Return , arr = arr.splice(1,1); // Return ; arr = arr = ; arr.splice(2,0,"a","b"); // Return ; arr =

push() and pop() methods

The push() and pop() methods allow you to work with arrays as if they were stacks. The push() method adds one or more new elements to the end of the array and returns its new length. The pop() method performs the reverse operation - it removes the last element of the array, reduces the length of the array, and returns the value it removed. Note that both of these methods modify the original array rather than creating a modified copy of it.

unshift() and shift() methods

The unshift() and shift() methods behave almost the same as push() and pop(), except that they insert and remove elements at the beginning of the array rather than at the end. The unshift() method shifts existing elements to larger indices to free up space, adds the element or elements to the beginning of the array, and returns the new length of the array. The shift() method removes and returns the first element of the array, shifting all subsequent elements down one position to take up the space vacated at the beginning of the array.

In JavaScript. Here we will continue our acquaintance with the Arrays. Let's talk about the length property - how to find out: how many elements does the Array contain?

Let's learn how to add elements to the beginning and end of the Array - these are the unshift and push methods, respectively.

And also using the shift and pop methods we can remove elements from the beginning and end of the Array!

Essentially, an Array is an object consisting of a certain number of different elements.

The length property allows you to find out the number of elements in the Array.

For example, let's take the Array of seven days of the week, familiar to us from the previous topic.

var days = ["Mon." , "Tue.";

Let's find out and display the number of array elements. To do this, it is necessary, as you see in the example below, to create a variable whose value will be the array of interest to us, for which, in turn, the length property is specified.

array.length - this code gives us the number of elements of the Array (Where array - Array name) .

var days = ["Mon." , "Tue.", "Wed.", "Thu.", "Friday.", "Sat.", "Sun."] ;

var count = days .length ;

document.write(count);

Thus, in the count variable we placed a number equal to the number of elements of the Array.

This is how the length property works.

Push method - adds an element to the end of the Array.

In order to start working with methods for adding elements, you need to create some kind of Array.

Below I have created a “Friends” Array - friends .

, "Vyacheslav", "Alexey"] ;

Now we need to add an element, that is, another Name to the end of the Array.

There is a push method for this - it adds an element to the end of the Array. It looks like this:

, "Vyacheslav", "Alexey"];

friends.push("Jacob"); /*Add an element to the end of the Array*/

document.write(+friends.length);

document.write("

" + friends); /*Output the entire Array*/

document.write("

" + friends); /*Output the last 5th element of the Array*/

Nastya, Grigory, Vyacheslav, Alexey, Yakov

Yakov

To test the work of the push method in the example above, we displayed the number of elements of the friends Array using the length property - there were 5 of them. Then we output the entire friends Array, as well as the last element of the Array .

Now you can see for yourself that the element has been added to the end of the Array!

unshift method - adds an element to the beginning of the Array.

Here we will again refer to the friends Array.

var friends = ["Nastya", "Gregory", "Vyacheslav", "Alexey"] ;

Now we need to add an element to the beginning of the Array. There is a method called unshift for this.

var friends = ["Nastya", "Grigory", "Vyacheslav", "Alexey"];

friends.unshift("Boris"); /*Add an element to the beginning of the Array*/

document .write ( "The number of elements in the Array is " + friends .length );

document.write("

" + friends); /*Output the entire Array*/

document.write("

" + friends); /*Output the first element of the Array*/

The number of elements in the Array is 5

Boris, Nastya, Grigory, Vyacheslav, Alexey

Boris

To test the unshift method, we output the number of elements of the friends Array using the length property, then output the entire friends Array, as well as the first element of the Array (remember that the numbering of Array elements starts from 0) .

Now, as you can see, the element has been added to the beginning of the Array!

pop method - removes the last element from the Array.

And again we are working with the “Friends” Array

var friends = ["Nastya", "Gregory", "Vyacheslav", "Alexey"] ;

Using the pop method we remove the last element from the Array:

var friends = ["Nastya", "Grigory", "Vyacheslav", "Alexey"];

friends.pop(); /*Remove the last element from the Array*/

document .write ( "The number of elements in the Array is " + friends .length );

document.write("

" + friends); /*Output the entire Array*/

document.write("

" + friends ); /*Output the last element of the Array. To do this, take the total number of elements of the Array - friends.length and, since the numbering in the array starts from zero, subtract 1 from this number*/

Nastya, Grigory, Vyacheslav

Vyacheslav

To make the pop method clearer, we again displayed the number of elements of the Array using the length property, then displayed the entire friends Array - without the last element removed.

And also the last element of the newly obtained Array was displayed . To output the last element, using the length property, we took the total number of remaining elements in the Array (3) and subtracted 1 from it. Thus, we output the last element of the array, number 2. But this is the third element, since the numbering in the Array starts from 0!!!

The shift method removes the first element from the Array.

Before us, as before, is the “Friends” Array

var friends = ["Nastya", "Gregory", "Vyacheslav", "Alexey"] ;

Using the shift method, we remove the first element from the Array:

var friends = ["Nastya", "Grigory", "Vyacheslav", "Alexey"];

friends.shift(); /*Remove the first element from the Array*/

document .write ( "The number of elements in the Array is " + friends .length );

document.write("

" + friends); /*Output the entire Array*/

document.write("

" + friends); /*Output the first element of the Array.*/

The number of elements in the Array is 3

Grigory, Vyacheslav, Alexey

Gregory

And finally, to test the operation of the shift method, we displayed the number of elements of the newly obtained Array using the length property, then displayed the entire friends Array - without the first element removed.

And also displayed the first element of the Array . Numbering in the Array starts from 0!!!

Let me remind you and myself of one interesting point from this article!

In order to find out the number/index of the last element of the Array, you need from among its elements (i.e. from) Subtract one!!!

We have already worked with this in the topic point.

A good way to illustrate this point would be to continue the example from the topic point where we looked at the Array of the seven days of the week.

var days = ["Mon." , "Tue.", "Wed.", "Thu.", "Friday.", "Sat.", "Sun."] ;

var count = days .length ; /*Create a variable count in which we enter the number of elements of the Array days*/

document .write ( "The number of elements in the days Array is " + count );

document.write("

The number of the last element of the days Array is the number " + (count - 1 ) );

The number of elements in the days Array is 7

The number of the last element of the Array is the number 6

So, with this example, we at the same time once again noted the fact that the numbering in the Array starts from 0. And, as you can see from this example, the number of the 7th element of the array is the number 6.

At the end of this topic we will also do our homework. Again, try to solve it yourself.

Homework on removing from... and adding elements to an Array in Javascript has the following content:

1. Create an array of fruits: orange, banana, pear.
2. Display how many this moment you have an array of fruits.
3. Using the methods learned in the previous lesson, add two fruits to the end of the array - an apple and a pineapple, and to the beginning of the array - a grapefruit.
4. Display on the screen how many fruits you currently have in the array.
5. Using the techniques learned in the previous lesson, remove the last and first element from the array.
6. Display on the screen how many fruits you currently have in the array.

var fruit = ["Orange","Banana","Pear"];
document .write (fruit + "

" )
document .write("Currently in my cart " + fruit.length + " fruit" + "

fruit .push("Apple", "Pineapple"); // Add elements to the END of the array
fruit .unshift("Grapefruit"); // Add elements to the BEGINNING of the array
document .write (fruit + "

" )
document .write("Currently in my cart " + fruit.length + " fruit" + "

fruit.pop(); // Remove the LAST element from the Array
fruit.shift(); // Remove the FIRST element from the Array
document .write (fruit + "

" )
document .write("Currently in my cart " + fruit.length + " fruit" );

Orange, Banana, Pear

There are currently 3 fruits in my basket

Grapefruit, Orange, Banana, Pear, Apple, Pineapple

There are currently 6 fruits in my basket

Orange, Banana, Pear, Apple

There are currently 4 fruits in my basket

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 a 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 starting from specified index to the end of the array. 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

The push() method adds one or more elements to the end of an array and returns the new length of the array.

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 arr .push(element1 [, ...[, elementN ]]) Parameters element N The element(s) to add to the end of the array. Return value Examples Adding elements to an array

The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

Let sports = ["soccer", "baseball"] let total = sports.push("football", "swimming") console.log(sports) // ["soccer", "baseball", "football", "swimming" "] console.log(total) // 4

Merging two arrays

This example uses apply() to push all elements from a second array.

Do not use this method if the second array (moreVegs in the example) is very large, because the maximum number of parameters that one function can take is limited in practice. See apply() for more details.

Let vegetables = ["parsnip", "potato"] let moreVegs = ["celery", "beetroot"] // Merge the second array into the first one // Equivalent to vegetables.push("celery", "beetroot") Array.prototype.push.apply(vegetables, moreVegs) console.log(vegetables) // ["parsnip", "potato", "celery", "beetroot"]

Using an object in an array-like fashion

As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

Note that we don"t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array-and it just works, thanks to the way JavaScript allows us to establish the execution context however we please.

Let obj = ( length: 0, addElem: function addElem(elem) ( // obj.length is automatically incremented // every time an element is added. .push.call(this, elem) ) ) // Let's add some empty objects just to illustrate. obj.addElem(()) obj.addElem(()) console.log(obj.length) // → 2

Note that although obj is not an array, the method push successfully incremented obj "s length property just like if we were dealing with an actual array.

Specifications Specification Status Comment
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
Standard
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of "Array.prototype.push" in that specification.
Standard
ECMAScript Latest Draft (ECMA-262)
The definition of "Array.prototype.push" in that specification.
Draft
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.jspush
Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera 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

In this article we will look at standard JavaScript arrays with numeric indexes. Arrays are declared using square brackets:

var fruits = ["Apple", "Orange", "Donkey"]

To extract an element, place its index in square brackets. First index 0 :

var fruits = ["Apple", "Orange", "Donkey"] alert(fruits) alert(fruits) alert(fruits)

We can also get the length of a JavaScript array:

var fruits = ["Apple", "Orange", "Donkey"] alert(fruits.length)

Oops! We created an array with two fruits and a donkey. Now we need to remove the donkey.

pop and push methods

The pop method in JavaScript removes an element from an array and returns it.

The following example shows how "Donkey" is retrieved from an array:

var fruits = ["Apple", "Orange", "Donkey"] alert("I'm removing "+fruits.pop()) // Now we only have ["Apple","Orange"] alert("Now the size of the array : "+fruits.length) // donkey removed

Note that pop modifies the array itself.

Pop's counterpart is the push method, which adds an element to an array. For example, we forgot to add a peach:

var fruits = ["Apple", "Orange"] fruits.push("Peach"); // now we have ["Apple", "Orange", "Peach"] alert("Last element:"+fruits)

  • Create an array of styles with elements “Jazz”, “Blues”;
  • Add the value "Rock'n'Roll";
  • Replace the second value from the end with the value "Classic". You should end up with an array: “Jazz”, “Classic”, “Rock’n’Roll”. The code should work for any array length;
  • Retrieve the last value from the array and display it via alert .
  • Solution

    // 1 var styles = ["Jazz", "Bluez"] // 2 styles.push("Rock"n"Roll") // or: styles = "Rock"n"Roll" // 3 styles = "Classic " // 4 alert(styles.pop())

    Shift/unshift methods

    The shift/unshift methods operate on the end of the array, but you can also use shift to shift the elements up (the first value of the array is removed as the elements shift). The unshift method allows JavaScript to add an element to an array from the end:

    var fruits = ["Apple", "Orange"] var apple = fruits.shift() // now we only have ["Orange"] fruits.unshift("Lemon") // now we have ["Lemon", "Orange"] alert(fruits.length) // 2

    Both shift and unshift can operate on multiple elements at once:

    var fruits = ["Apple"] fruits.push("Orange","Peach") fruits.unshift("Pineapple","Lemon") // now the array looks like this: ["Pineapple", "Lemon", "Apple" ", "Orange", "Peach"]

    Self-administered task

    Write the code to display a random value from the arr array via alert:

    var arr = ["Plum","Orange","Donkey","Carrot","JavaScript"]

    Note: The code to get a random number from the minimum to the maximum value (inclusive) is as follows:

    var rand = min + Math.floor(Math.random()*(max+1-min))

    Solution

    We need to extract a random number from 0 to arr.length-1 (inclusive):

    var arr = ["Plum","Orange","Donkey","Carrot","JavaScript"] var rand = Math.floor(Math.random()*arr.length) alert(arr)

    Iterating over an array

    In JavaScript, iterating through an array is done using a for loop:

    var fruits = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"] for(var i=0; i=0 check faster than i . Which in JavaScript speeds up searching in an array.

    Using length to trim an array

    Using the length property, you can truncate an array like this:

    You specify the length and the browser truncates the array.

    Array is an object, so what does this mean?

    In fact, in JavaScript, Array is an Object, augmented automatic installation lengths and special methods.

    This is different from the concept in other languages, where arrays represent a contiguous segment of memory. This is also different from a queue or stack based on linked lists.

    Non-numeric array keys

    Keys are numbers, but they can have any name:

    arr = arr = 5 arr.prop = 10 // don't do this

    In JavaScript, arrays are hash tables, which have performance advantages but also certain disadvantages.

    For example, push/pop only works on the outermost elements of an array, so they are incredibly fast.

    push only works with the end:

    var arr = ["My", "array"] arr.push("something") alert(arr) // string "array"

    The shift/unshift methods are slow because they need to renumber the entire array. The splice method can also cause the numbering to change:

    So shift/unshift are slower than push/pop . The larger the array, the longer it takes JavaScript to sort the array.

    Self-administered task

    What will be the result? Why?

    arr = ["a", "b"] arr.push(function() ( alert(this) )) arr() // ?

    Solution

    Since arrays are objects, arr .. is actually a method call on an object such as obj method:

    arr() // same as arr() // syntactically incorrect, but conceptually the same: arr.2() // rewritten in the same style as obj.method() this = arr in this case is passed to the function, so the contents of arr are printed. arr = ["a", "b"] arr.push(function() ( alert(this) )) arr() // "a","b",function

    Sparse arrays, length description

    The length property allows you to get not the size of an array in JavaScript, but the last index + 1. This is important when we are talking about sparse arrays, with “gaps” in the indices.

    In the following example, we will add two elements to the empty fruits , but the length value will remain 100 :

    var fruits = // empty array fruits = "Peach" fruits = "Apple" alert(fruits.length) // 100 (but there are only 2 elements in the array)

    If you try to output a sparse array, the browser will return the missing index values ​​as empty elements:

    var fruits = // empty array fruits = "Peach" fruits = "Apple" alert(fruits) // ,Peach,Apple (or something like that)

    But an array is an object with two keys. Missing values ​​do not take up space.

    Sparse arrays behave weirdly when array methods are applied to them. They have no idea that indexes are missing:

    var fruits = fruits = "Peach" fruits = "Apple" alert(fruits.pop()) // pop "Apple" (at index 9) alert(fruits.pop()) // don't pop given element(at index 8)

    Try to avoid sparse arrays. In any case, their methods will not work normally. Use Object instead.

    Removing from an array

    As we know, arrays are objects, so we could use delete to remove a value:

    var arr = ["Go", "to", "home"] delete arr // now arr = ["Go", undefined, "home"] alert(arr) // not defined

    You can see that the value is removed, but not in the way we would like, because the array contains an unspecified element.

    The delete operator removes a key-value pair and that's it. Naturally, since the array is only a hash, the position of the removed element becomes undefined.

    Most often we need to remove an element without leaving “holes” between the indices. There is another method that will help us with this.

    splice method

    The splice method can remove elements and replace them in JavaScript multidimensional arrays. Its syntax is:

    arr.splice(index, deleteCount[, elem1, ..., elemN])

    Removes the deleteCount element starting at index and then inserts elem1, ..., elemN in its place.

    Let's look at a few examples:

    var arr = ["Go", "to", "home"] arr.splice(1, 1) // remove 1 element starting at index 1 alert(arr.join(",")) // ["Go ", "home"] (1 element removed)

    So you can use splice to remove one element from an array. The array element numbers are shifted to fill the space:

    var arr = ["Go", "to", "home"] arr.splice(0, 1) // remove 1 element, starting from index 0 alert(arr) // "to" became the first element

    The following example shows how to replace elements:

    The splice method returns an array of removed elements:

    var arr = ["Go", "to", "home", "now"]; // remove the first 2 elements var removed = arr.splice(0, 2) alert(removed) // "Go", "to" =0; i--) ( if (c[i] == cls) c.splice(i,1) ) elem.className = c.join(" ") ) var obj = ( className: "open menu" ) removeClass(obj , "open") removeClass(obj, "blabla") alert(obj.className) // menu

    In the above example, the variable c is set at the beginning of the loop and i is set to its last index.

    The loop itself runs in the opposite direction, ending with the condition i>=0. This is done because i>=0 is checked faster than i . Which speeds up searching for properties in c .

    slice method

    You can extract part of an array using the slice(begin[, end]) method: var arr = ["Why", "learn", "JavaScript"]; var arr2 = arr.slice(0,2) // takes 2 elements, starting at 0 alert(arr2.join(", ")) // "Why, learn"

    Please note that this method does not change the number of elements in the array in JavaScript, but copies part of it.

    You can omit the second argument to get all elements starting at a specific index:

    var arr = ["Why", "learn", "JavaScript"]; var arr2 = arr.slice(1) // takes all elements starting from 1 alert(arr2.join(", ")) // "learn, JavaScript"

    The method supports negative indexes, just like String#slice .

    reverse method

    Another useful method is reverse . Let's say I want to get the last part of a domain, for example "com" from "my.site.com". Here's how to do it:

    var domain = "my.site.com" var last = domain.split(".").reverse() alert(last)

    Note that JavaScript arrays support a complex syntax (reverse()) for calling a method and then retrieving an element from the resulting array.

    You can create longer calls like reverse() 0] arr.sort() alert(arr) // 1, 15, 2

    Run the above code. You will get the order 1, 15, 2. This is because the method converts everything to a string and uses lexicographic order by default.

    Related publications