The JavaScript language provides rich features for working with arrays, which are implemented using the methods of the Array object. Consider the application of these methods
Copying an array. slice()
Copying an array can be shallow or shallow (shallow copy) and deep (deep copy).
For shallow copying, it is enough to assign the value of another variable that stores the array to a variable:
const users = ["Tom", "Sam", "Bill"]; console log(users); // ["Tom", "Sam", "Bill"] const people = users; // shallow copy people[1] = "Mike"; // change the second element console log(users); // ["Tom", "Mike", "Bill"]
In this case, the people variable, after being copied, will point to the same array as the users variable. Therefore, when changing elements in people, the elements in users will also change, since in fact this is the same array.
This behavior is not always desirable. For example, we want the variables to point to separate arrays after copying. And in this case, you can use deep copying with the slice() method :
const users = ["Tom", "Sam", "Bill"]; console.log(users); // ["Tom", "Sam", "Bill"] const people = users.slice(); // deep copy people[1] = "Mike"; // change the second element console.log(users); // ["Tom", "Sam", "Bill"] console.log(people); // ["Tom", "Mike", "Bill"]
In this case, after copying, the variables will point to different arrays, and we can change them separately from each other.
But here it is worth noting that the same copying can essentially be done using the spread operator … :
const users = ["Tom", "Sam", "Bill"]; console.log(users); // ["Tom", "Sam", "Bill"] const people = [...users]; people[1] = "Mike"; // change the second element console.log(users); // ["Tom", "Sam", "Bill"] console.log(people); // ["Tom", "Mike", "Bill"]
Also, the method slice()allows you to copy part of the array. To do this, it takes two parameters:
slice(start_index, end_index)
The first parameter points to the starting index of the element from which are used to fetch values from the array. And the second parameter is the end index to which you want to copy.
For example, let’s select elements in a new array, starting from index 1 to index 4, not including:
const users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const people = users.slice(1, 4); console.log(people); // ["Sam", "Bill", "Alice"]
And since array indexing starts from zero, the new array will contain the second, third and fourth element.
If only the start index is specified, then copying is performed to the end of the array:
const users = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const people = users.slice(2); // from the second index to the end console.log(people); // ["Bill", "Alice", "Kate"]
push()
The method push()adds an element to the end of the array:
const people = []; people.push("Tom"); people.push("Sam"); people.push("Bob","Mike"); console.log("In the people array of elements: ", people.length); console log(people); // ["Tom", "Sam", "Bob", "Mike"]
pop()
The method pop()removes the last element from the array:
const people = ["Tom", "Sam", "Bob", "Mike"]; const lastPerson = people.pop(); // extract the last element from the array console.log(lastPerson ); // Mike console.log(people); // ["Tom", "Sam", "Bob"]
shift()
The method shift()retrieves and removes the first element from the array:
const people = ["Tom", "Sam", "Bob", "Mike"]; const firstPerson = people.shift(); // extract the first element from the array console.log(firstPerson); // Tom console.log(people); // ["Sam", "Bob", "Mike"]
unshift()
The unshift() method adds a new element to the beginning of the array:
const people = ["Tom", "Sam", "Bob"]; people.unshift("Alice"); console.log(people); // ["Alice", "Tom", "Sam", "Bob"]
Removing an element by index. splice()
The method splice()removes elements from a specific index. For example, removing elements from the third index:
const people = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const deleted = people.splice(3); console.log(deleted); // [ "Alice", "Kate" ] console.log(people); // [ "Tom", "Sam", "Bill" ]
The splice method returns the removed elements as a new array.
In this case, the deletion is from the beginning of the array. If you pass a negative index, then the removal will be performed from the end of the array. For example, let’s remove the last element:
const people = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const deleted = people.splice(-1); console.log(deleted); // [ "Kate" ] console.log(people); // ["Tom", "Sam", "Bill", "Alice"]
An additional version of the method allows you to set the number of elements to remove. For example, let’s remove three elements from the first index:
const people = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const deleted = people.splice(1, 3); console.log(deleted); // ["Sam", "Bill", "Alice"] console.log(people); // ["Tom", "Kate"]
Another version of the splice method allows you to insert new elements in place of the removed elements:
const people = ["Tom", "Sam", "Bill", "Alice", "Kate"]; const deleted = people.splice(1, 3, "Ann", "Bob"); console.log(deleted); // ["Sam", "Bill", "Alice"] console.log(people); // ["Tom", "Ann", "Bob", "Kate"]
In this case, we remove three elements from the 1st index and insert two elements instead.
concate()
The method concat() is used to combine arrays. It returns the concatenated array as a result:
const men = ["Tom", "Sam", "Bob"]; const women = ["Alice", "Kate"]; const people = men.concat(women); console.log(people); // ["Tom", "Sam", "Bob", "Alice", "Kate"]
join()
The method join()concatenates all array elements into one string using a specific delimiter, which is passed as a parameter:
const people = ["Tom", "Sam", "Bob"]; const peopleToString = people.join("; "); console.log(peopleToString); // Tom; Sam; Bob
join() The separator between array elements is passed to the method . In this case, a semicolon and a space (“; “) will be used as a separator.
sort()
The method sort()sorts the array in ascending order:
const people = ["Tom", "Sam", "Bob"]; people.sort(); console.log(people); // ["Bob", "Sam", "Tom"]
It’s worth noting that by default, the method sort()treats the array elements as strings and sorts them alphabetically. Which can lead to unexpected results, such as:
const numbers = [200, 15, 5, 35]; numbers.sort(); console.log(numbers); // [15, 200, 35, 5]
Here we want to sort an array of numbers, but the result might be confusing: [15, 200, 35, 5]. In this case, we can customize the method by passing a sort function to it. We define the logic of the sort function ourselves:
const numbers = [200, 15, 5, 35]; numbers.sort( (a, b) => a - b); console.log(numbers); // [5, 15, 35, 200]
The sort function gets two adjacent array elements. It returns a positive number if the first element should come before the second element. If the first element is to be placed after the second, then a negative number is returned. If the elements are equal, 0 is returned.
reverse()
The method reverse()flips the array backwards:
const people = ["Tom", "Sam", "Bob"]; people.reverse(); console.log(people); // ["Bob", "Sam", "Tom"]
Finding the index of an element
The indexOf () and lastIndexOf() methods return the index of the first and last occurrence of an element in an array. For example:
const people = ["Tom", "Sam", "Bob", "Tom", "Alice", "Sam"]; const firstIndex = people.indexOf("Tom"); const lastIndex = people.lastIndexOf("Tom"); const otherIndex = people.indexOf("Mike"); console.log(firstIndex); // 0 console.log(lastIndex); // 3 console.log(otherIndex); // -1
firstIndex is 0 because the first occurrence of the string “Tom” in the array is at index 0 and the last at index 3.
If the element is not in the array, then in this case the methods indexOf()and lastIndexOf()return the value -1.
Checking if an element exists
The includes() method checks if the array contains the value passed to the method via a parameter. If there is such a value, then the method returns true, if there is no value in the array, then false. For example:
const people = ["Tom", "Sam", "Bob", "Tom", "Alice", "Sam"]; console.log(people.includes("Tom")); // true - Tom is in the array console.log(people.includes("Kate")) // false - Kate is not in the array
The includes() method takes the index from which to start searching as its second parameter :
const people = ["Tom", "Sam", "Bob", "Tom", "Alice", "Sam"]; console.log(people.includes("Bob", 2)); // true console.log(people.includes("Bob", 4)) // false
In this case, we see that when searching from the 2nd index, the array contains the string “Bob”, while starting from the 4th index, this string is missing.
If this parameter is not passed, then by default the search starts from the 0th index.
When passing a negative value, the search starts from the end
const people = ["Tom", "Sam", "Bob", "Tom", "Alice", "Sam"]; console.log(people.includes("Tom", -2)); // false - 2nd index from the end console.log(people.includes("Tom", -3)) // true - 3rd index from the end
every()
The every() method checks if all elements match a certain condition:
const numbers = [ 1, -12, 8, -4, 25, 42 ];
const passed = numbers.every(n => n > 0);
console.log(passed); // false
every() A function that represents the condition is passed to the method as a parameter. This function takes an element as a parameter and returns true(if the element matches the condition) or false(if it doesn’t).
If at least one element does not match the condition, then the method every()returns the value false.
In this case, the condition is specified using a lambda expression n => n > 0that tests whether the element is greater than zero.
some()
The method some()is similar to the method every(), only it checks if at least one element matches the condition. And in this case, the method some()returns true. If there are no elements matching the condition in the array, then the value is returned false:
const numbers = [ 1, -12, 8, -4, 25, 42 ]; const passed = numbers.some(n => n > 0); console.log(passed); // true
filter()
The method filter(), like some(), every()takes a condition function. But at the same time, it returns an array of those elements that meet this condition:
const numbers = [ 1, -12, 8, -4, 25, 42 ]; const filteredNumbers = numbers.filter(n => n > 0); console.log(filteredNumbers); // [1, 8, 25, 42]
forEach() and map()
The forEach() and map() methods iterate over the elements and perform certain operations on them. For example, let’s use the method method forEach()to calculate the squares of the numbers in an array:
const numbers = [ 1, 2, 3, 4, 5, 6]; numbers.forEach(n => console.log("Squared number", n, "equal", n * n ) );
The method forEach()takes as a parameter a function that has one parameter – the current element of the array being iterated over. And in the body of the function, various operations can be performed on this element.
Console output of the program:
The square of the number 1 is 1
The square of the number 2 is 4
The square of the number 3 is 9
The square of the number 4 is 16
The square of the number 5 is 25
The square of the number 6 is 36
The map() method is similar to the method forEach, it also takes as a parameter a function that performs operations on the iterated elements of the array, but the map() method returns a new array with the results of operations on the array elements.
For example, let’s apply the map method to calculate the squares of the numbers in an array:
const numbers = [ 1, 2, 3, 4, 5, 6]; const squares = numbers.map(n => n * n); console.log(squares); // [1, 4, 9, 16, 25, 36]
The function that is passed to the method map()receives the current iterated element, performs operations on it, and returns some value. This value is then passed into the resulting arrays quares
Search in an array
The find() method returns the first element in an array that matches some condition. The method find takes a condition function as a parameter:
const numbers = [1, 2, 3, 5, 8, 13, 21, 34]; // get the first element that is greater than 10 let found = numbers.find(n => n > 10 ); console.log(found); // 13
In this case, we get the first element that is greater than 10. If the element that matches the condition is not found, then returns undefined.
The findIndex method also accepts a condition function, only returning the index of the first array element that matches that condition:
const numbers = [1, 2, 3, 5, 8, 13, 21, 34]; // get the index of the first element that is greater than 10 let foundIndex = numbers.findIndex(n => n > 10 ); console.log(foundIndex); // 5
If the element is not found, then -1 is returned.
flat method and array conversion
The flat() method simplifies the array, given the specified element nesting:
const people = ["Tom", "Bob", ["Alice", "Kate", ["Sam", "Ann"]]]; const flattenPeople = people.flat(); console.log(flattenPeople); // ["Tom", "Bob", "Alice", "Kate", ["Sam", "Ann"]]
That is, the method flat()actually transfers elements from nested arrays to the outer array of the topmost level. However, we see that the elements of the array of the second nesting level have moved into the array of the first nesting level, but nevertheless are still in the nested array. The point is that the flat()default method applies only to nested arrays of the first nesting level. But we can pass a nesting level to the method:
const people = ["Tom", "Bob", ["Alice", "Kate", ["Sam", "Ann"]]]; const flattenPeople = people.flat(2); console.log(flattenPeople); // ["Tom", "Bob", "Alice", "Kate", "Sam", "Ann"]
If the array contains nested arrays of much deeper nesting levels, or we don’t even know what nesting levels the array has, but we want all elements to be converted into a single array, then we can use the value Infinity:
const people = ["Tom", "Bob", ["Alice", "Kate", ["Sam", "Ann"]]]; const flattenPeople = people.flat(Infinity); console.log(flattenPeople); // ["Tom", "Bob", "Alice", "Kate", "Sam", "Ann"]