JavaScript Array Methods

JavaScript incorporates a variety of native methods that enable developers to effectively engage with arrays. The language facilitates numerous operations, including the addition, removal, modification, or retrieval of elements, as well as transforming or looping through arrays.

What do you understand by an Array?

In JavaScript, an array is a distinct type of variable designed to hold multiple values simultaneously. Arrays enable us to manage lists of data in a manner that is both efficient and effective. Each array is made up of elements, with every element assigned a numerical index that begins at 0. This unique variable type can accommodate various data types, including numbers, strings, objects, or even other arrays nested within. Arrays are primarily utilized for tasks such as managing collections, iterating through data, and performing sorting or filtering operations.

Array Basic Methods

1. Array toString in JavaScript

This technique constructs an array represented as a string with elements separated by commas. Importantly, this method does not modify the original array and is essential for displaying the array's contents as a string.

Example

Example

const names = ["Yashraj", " Thomas", " Kate"];

console.log("Array to String is", names.toString());

Output:

Output

Array to String is Yashraj, Thomas, Kate

Explanation:

In the preceding example, we declared a variable called names with the const keyword. We initialized it with an array that contains a collection of names. Subsequently, we employed the toString method to convert the array into a unified string and outputted the result to the console.

2. Array at in JavaScript

It retrieves the element located at a designated index within an array. This can be implemented for both positive and negative indices. Positive indices initiate from the beginning of the array (0-based), while negative indices count backward from the array's end.

Note: The at method is a new method introduced in ECMAScript 2022 (ES13). It won't run in the older environment. It will work perfectly in the ECMAScript 2022 (ES13) supported environment.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

console.log("Second Element is", names.at(1)); // Access second element

console.log("Last Element is", names.at(-1)); // Access last element

Output:

Output

Second Element is Thomas

Last Element is Kate

Explanation:

In the previous illustration, we declared a variable referred to as names with the const keyword and initialized it with an array that contains a collection of names. By employing the at method available for arrays, we retrieved both the second element and the last element from the array and printed them to the console.

In the event that your environment lacks support for the at method, you may utilize the subsequent code:

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];



console.log("Second Element is", names[1]);           // Access second element

console.log("Last Element is", names[names.length-1]); // Access last element

Output:

Output

Second Element is Thomas

Last Element is Kate

3. Array forEach in JavaScript

The forEach function is an inherent method designed to invoke a specified function for every element within an array. It does not generate a new array nor alter the existing array; instead, its primary purpose is to facilitate iteration over the elements.

Example

Example

const seasons = ["spring", "summer", "winter", "autumn"];



seasons.forEach((item) => {

    console.log(item);

});

Output:

Output

spring

summer

winter

autumn

Explanation:

In the code provided above, we established a variable called season and initialized it with an array that contains the names of different seasons. By employing the forEach method, we iterate through each element within the array and output the results to the console.

4. Array join in JavaScript

It combines every element of an array into a single string. The second argument acts as an optional custom delimiter; if it is not provided, a comma will be used as the default separator. This functionality is useful for creating formatted strings from the items within an array.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

console.log("Joined Elements are");

console.log(names.join(" - "));

Output:

Output

Joined Elements are

Yashraj - Thomas - Kate

Explanations:

In the preceding illustration, we declared a variable called names using the const keyword and assigned an array containing names to it. By employing the join method, we concatenated the array elements using a hyphen (-) as the separator and displayed the resulting string in the console.

5. Array pop in JavaScript

This method removes the final element from the array, consequently altering its length. You will observe that it directly affects the specified array. When the pop function is applied to an empty array, it yields an undefined result.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const lastName = names.pop();

console.log("Removed Element is", lastName);

console.log("Updated Array is", names);

Output:

Output

Removed Element is Kate

Updated Array is [ 'Yashraj', 'Thomas' ]

Explanation:

In the preceding example, we established a variable called names using the const keyword and initialized it with an array that contains a collection of names. By employing the pop method, we eliminated the final element from the array and displayed the result in the console.

6. Array push in JavaScript

The push function is employed to insert one or several elements at the conclusion of an array, subsequently returning the modified array that reflects a new length. This method attaches the newly added elements to the end of the existing array.

Example

Example

const names = ["Yashraj", "Thomas"];

const newLength = names.push("Kate");

console.log("New length of the array is", newLength);

console.log("Updated array is", names);

Output:

Output

New length of the array is 3

Updated array is [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the code presented above, we defined an array called names using the const keyword and populated it with a collection of names. We then employed the push method to add an element to the end of this array. Finally, we displayed the output in the console.

7. Array shift in JavaScript

The shift method for arrays effectively removes the first element from the array. This operation is performed by altering the original array and repositioning each subsequent element to the left following the removal. In instances where the array is empty, the method will return no value.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const firstName = names.shift();

console.log("Removed element:", firstName);

console.log("Updated array:", names);

Output:

Output

Removed element: Yashraj

Updated array: [ 'Thomas', 'Kate' ]

Explanation:

In the example provided, we declared a variable called names using the const keyword and assigned an array of names to it. We then employed the shift method to eliminate the first item in the array and outputted this value to the console.

8. Array unshift in JavaScript

The unshift function serves the purpose of appending new elements at the beginning of an array, subsequently returning the modified array with an altered length. This method effectively shifts all existing items to the right of the specified location for the new element insertion.

Example

Example

const names = ["Thomas", "Kate"];

const newLength = names.unshift("Yashraj");

console.log("New length of the array:", newLength); //

console.log("Updated array:", names);

Output:

Output

New length of the array: 3

Updated array: [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the example provided above, we established a variable called names using the const keyword, to which we assigned an array containing several names. By making use of the unshift method, we add a new element to the start of the array. In this case, we added the name Yashraj to the array and subsequently displayed it in the console.

9. Array concat in JavaScript

The concat function is utilized to merge or combine two or more arrays into a fresh array. This operation does not alter the original array.

Example

Example

const names1 = ["Yashraj", "Thomas"];

const names2 = ["Kate", "Kartik"];

const combinedNames = names1.concat(names2);

console.log("Combined Names are", combinedNames);

Output:

Output

Combined Names are [ 'Yashraj', 'Thomas', 'Kate', 'Kartik' ]

Explanation:

In the preceding example, we established two variables identified as names1 and names2 utilizing the const keyword, both of which are assigned an array containing names. By employing the concat method, we merged the two arrays and assigned the result to a variable called combinedNames. We then outputted the final result to the console.

10. Array copyWithin in JavaScript

This technique creates a shallow copy of a designated segment of an array and places it in another position within the same array. After executing this operation, the method returns the original array, which remains unchanged in its overall size. The parameters for this method include the target index and the starting index.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Kartik"];

names.copyWithin(1, 2);

console.log(names);

Output:

Output

[ 'Yashraj', 'Kate', 'Kartik', 'Kartik' ]

Explanation:

In the preceding example, we created a variable called names with the const keyword and initialized it with an array that includes various names. By employing the copyWithin method, we performed a shallow copy to a different position within the same array and then displayed the result in the console.

11. Array flat in JavaScript

The flat function generates a new array by flattening the elements of sub-arrays to a specified depth, effectively incorporating them into a singular array. By default, the depth is set to 1.

Example

Example

const nestedArray = ["Yashraj", ["Thomas", ["Kate"]]];

const flatArray = nestedArray.flat(2);

console.log("Array Flat:", flatArray);

Output:

Output

Array Flat: [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the preceding illustration, we created a variable called nestedArray utilizing the const keyword, which holds an array filled with names. This is referred to as a nested array, indicating that it contains arrays within an array. Subsequently, we defined an additional variable, flatArray, and assigned it the value of nestedArray.flat(2), which effectively decreases the depth of the nested structure. The parameter 2 signifies that the array should be flattened to a depth of 2. Finally, we output the result to the console.

12. Array splice in JavaScript

The splice function allows for modification of an array's contents by either removing current elements or inserting new ones directly. It produces a new shallow copy of the segment of the array ranging from the start index to (but excluding) the end index.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const removed = names.splice(1, 1, "Kartik");

console.log("Removed elements:", removed);

console.log("Updated array:", names);

Output:

Output

Removed elements: [ 'Thomas' ]

Updated array: [ 'Yashraj', 'Kartik', 'Kate' ]

Explanation:

In the code presented above, we declared a variable called names using the const keyword and initialized it with an array populated with names. By employing the splice method, we modified an element within the array and printed the outcome to the console. Specifically, in the names.splice(1, 1, "Kartik") method call, the initial argument of 1 indicates that the operation should commence at index 1, which corresponds to the name Thomas. The second argument signifies that one element should be removed, which results in the removal of Thomas. The third argument specifies the new name that will take Thomas's place. Consequently, Thomas is substituted with Kartik.

13. Array toSpliced in JavaScript

The toSpliced function generates a fresh array that incorporates specified alterations, such as the addition or removal of an element, while leaving the original array unaltered. This method operates similarly to the slice method; however, unlike slice, which modifies the source array, toSpliced preserves the integrity of the original array by returning a new array that reflects the desired changes.

Note: The toSpliced is a new method introduced in ES2023. It won't run in an older environment. It will work perfectly in the ES2023-supported environment.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const newNames = names.toSpliced(1, 1, "Kartik");

console.log("New array:", newNames); 

console.log("Original array:", names);

Output:

Output

New array: [ 'Yashraj', 'Kartik', 'Kate' ]

Original array: [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the code provided, we created a variable called names using the const keyword and initialized it with an array of names. By utilizing the toSpliced method, we substituted Thomas with Kartik and displayed the result in the console. In the expression names.toSpliced(1, 1, "Kartik"), the first argument, 1, indicates that the operation should commence from index 1. Consequently, it begins with Thomas. The second argument is also 1, which specifies that one element should be removed, effectively deleting the element located at index 1, which is Thomas. The third argument, Kartik, represents the value we wish to insert in place of Thomas.

14. Array slice in JavaScript

Let's examine the functionality of the slice method. This method produces a new array while leaving the original array unaltered. It accepts two optional arguments: the starting index (inclusive) and the ending index (exclusive). In the absence of an end index, the slicing operation will continue until it reaches the end of the array. Additionally, negative indices are interpreted as counting backward from the end of the array.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Kartik"];

const slicedNames = names.slice(1, 3);	

console.log("Extracted portion:", slicedNames);

console.log("Original array:", names);

Output:

Output

Extracted portion: [ 'Thomas', 'Kate' ]

Original array: [ 'Yashraj', 'Thomas', 'Kate', 'Kartik' ]

Explanation:

In this instance, we declared a variable called names using the const keyword and initialized it with an array that holds various names. By employing the slice method, we were able to obtain a segment of the array and output the resulting portion to the console.

Searching Methods

1. Array indexOf in JavaScript

The indexOf function serves to identify the initial index at which a specified element exists within an array, returning -1 if the element is absent. This method employs strict equality (===) to ascertain whether the element is present.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Thomas"];

console.log("First occurrence:", names.indexOf("Thomas")); 

console.log("Index of not present element:", names.indexOf("Rahul"));

Output:

Output

First occurrence: 1

Index of not present element: -1

Explanation:

In the preceding code snippet, a variable called names is established using the const keyword, and it is assigned an array that contains a list of names. By employing the indexOf method, we can identify the position of the first instance of "Thomas." This initial occurrence of "Thomas" appears at index 1, and the elements from index 1 through index 3 are then displayed in the console.

2. Array lastIndexOf in JavaScript

The lastIndexOf function serves to retrieve the final index of a specified element within an array. In the event that the element cannot be located, it yields -1. This method evaluates for strict equality.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Thomas"];

console.log("First occurrence:", names.lastIndexOf("Thomas")); 

console.log("Index of not present element:", names.lastIndexOf("Rahul"));

Output:

Output

First occurrence: 3

Index of not present element: -1

Explanation:

In the preceding example, we established a variable referred to as names using the const keyword, to which an array containing names was assigned. By employing the lastIndexOf method, we can determine the final index of the specified element within the array. The last index of that element was then logged, and the outcome was presented in the console.

3. Array includes in JavaScript

The includes function is employed to determine if a specific element exists within the array. It yields true if the element is present and false if it is not. This method performs a check based on strict equality.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

console.log("Include's Thomas:", names.includes("Thomas"));

console.log("Include's Rahul:", names.includes("Rahul"));

Output:

Output

Include's Thomas: true

Include's Rahul: false

Explanation:

In the preceding example, we established a variable called names using the const keyword, and we assigned an array to it that comprises various names. By employing the includes method, we can determine if the array contains a specific element, and this method yields a Boolean result. In the expression names.includes("Thomas"), we verify if Thomas is present in the array. Since the array includes Thomas, it returns true; however, because it does not include Rahul, it returns false.

4. Array find in JavaScript

The find function is utilized to obtain the initial element from an array that meets the criteria established by a testing function. If no elements fulfill the specified condition, it will return undefined.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];  

const result = names.find((name) => name.startsWith("K"));  

console.log("First matching element:", result);

Output:

Output

First matching element: Kate

Explanation:

In the previously mentioned example, we created a variable called names using the const keyword and initialized it with an array that holds various names. By employing the find method, we retrieve the first item from the array that meets the specified criterion. In this instance, we obtain the first element that begins with the letter K, and subsequently output the result to the console.

5. Array findIndex in JavaScript

In a similar fashion, the findIndex function is employed to retrieve the index of the initial element within the specified array that satisfies a given testing condition. If none of the elements meet the criteria, the method will return -1.

Example

Example

const names = ["Yashraj", "King","Thomas", "Kate"];  

const index = names.findIndex((name) => name.startsWith("K"));  

console.log("Index of the matching element:", index);

Output:

Output

Index of the matching element: 1

Explanation:

In the preceding example, we declared a variable called names by employing the const keyword and initialized it with an array that holds the names. By leveraging the findIndex method, we can determine the index of the initial element that meets the specified criteria. In this case, we are retrieving the index of the first element that begins with the letter K and subsequently outputting the result to the console.

6. Array findLast in JavaScript

The findLast function serves to retrieve the last element of an array that meets a specified testing criterion. In the event that no elements satisfy the condition, it will return undefined.

Note: The findLast is a new method introduced in ES2023 (ECMAScript 2023). It won't run in an older environment. It will work perfectly in the ES2023-supported environment.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Kartik"];

const result = names.findLast((name) => name.startsWith("K"));

console.log("Last matching element:", result);

Output:

Output

Last matching element: Kartik

Explanation:

In the preceding example, we established a variable called names using the const keyword and assigned it an array that holds the names. By employing the findLast method, we retrieve the last element that meets the specified criteria. In this case, we obtain the last element that begins with the letter K and output the result to the console.

7. Array findLastIndex in JavaScript

The findLastIndex function is designed to yield the index of the last item within an array that satisfies the criteria established by the provided testing function. If no elements satisfy the specified condition, the function will return -1.

Note: The Array findLastIndex is a new method introduced in ES2023 / ECMAScript 2022. It won't run in an older environment. It will work perfectly in ES2023 / ECMAScript 2022.

Example

Example

const names = ["Yashraj", "Thomas", "Kate", "Kartik"];

const index = names.findLastIndex((name) => name.startsWith("K"));

console.log("Index of the last matching element:", index);

Output:

Output

Index of the last matching element: 3

Explanation:

In the preceding example, we created a variable called names using the const keyword and assigned it an array that holds various names. By employing the findLastIndex method, we are able to retrieve the index of the final element in the array that meets a specified condition. In this case, we obtain the last index of an element that begins with the letter K and output the result to the console.

Sorting Methods

1. Array sort in JavaScript

The sort function is employed to arrange the elements within an array, yielding a sorted Array as a result. By default, this method sorts elements as strings in ascending order, which may lead to inconsistent outcomes when sorting numerical values. For more intricate sorting requirements, one can supply a custom comparison function.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

names.sort();

console.log("Sorted alphabetically:", names);



const numbers = [10, 2, 5, 1];

numbers.sort((a, b) => a - b);

console.log("Numeric sort:", numbers);

Output:

Output

Sorted alphabetically: [ 'Kate', 'Thomas', 'Yashraj' ]

Numeric sort: [ 1, 2, 5, 10 ]

Explanation:

In the preceding example, we established a variable called names and another named numbers using the const keyword. The names variable is assigned an array that comprises names, while the numbers variable holds numerical values. By employing the sort method, we organize the array, which consists of string data types in alphabetical order and the numbers in ascending sequence.

2. Array reverse in JavaScript

The reverse function alters the sequence of elements within an array by reversing their order, directly modifying the original array in the process. Typically, it is employed alongside the sort method to achieve a descending arrangement of the elements.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

names.reverse();

console.log("Reversed order:", names);

Output:

Output

Reversed order: [ 'Kate', 'Thomas', 'Yashraj' ]

Explanation:

In the preceding illustration, we created a variable called names by employing the const keyword. This variable is assigned an array that includes various names. We then applied the reverse method to invert the order of the array and recorded the outcome in the console.

3. Array toSorted in JavaScript

The toSorted function rearranges the elements of an array in reverse order, altering the original array itself. It operates similarly to the sort method; however, unlike sort, which does not modify the original array and instead returns a new array containing the sorted elements, toSorted directly modifies the existing array.

Note: The toSorted is a new method introduced in ES2023. It won't run in an older environment. It will work perfectly in the ES2023-supported environment.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const sortedNames = names.toSorted();

console.log("Sorted array:", sortedNames);

console.log("Original array:", names);

Output:

Output

Sorted array: [ 'Kate', 'Thomas', 'Yashraj' ]

Original array: [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the previous illustration, we created a variable called names using the const keyword, to which we assigned an array containing various names. By employing the toSorted method, we arranged the array in alphabetical order and displayed the outcome in the console.

4. Array toReversed in JavaScript

The toReversed function serves to produce an array containing the elements arranged in reverse sequence, while leaving the original array unaltered. This feature is advantageous for reversing arrays without modifying the underlying data.

Note: The toReversed is a new method introduced in ES2023. It won't run in an older environment. It will work perfectly in the ES2023-supported environment.

Example

Example

const names = ["Yashraj", "Thomas", "Kate"];

const reversedNames = names.toReversed();

console.log("Reversed array:", reversedNames); 

console.log("Original array:", names);

Output:

Output

Reversed array: [ 'Kate', 'Thomas', 'Yashraj' ]

Original array: [ 'Yashraj', 'Thomas', 'Kate' ]

Explanation:

In the preceding example, we created a variable called names using the const keyword. This variable is assigned an array that contains a list of names. We employed the toReversed method to reverse the order of the array and subsequently logged the reversed array to the console.

5. Sorting Objects

In order to arrange objects within an array, it is necessary to create a custom comparison function that will be supplied to the sort method. The mechanism of sorting is established by formulating this function in accordance with the properties of the objects.

Example

Example

const students = [

    { name: "Yashraj", age: 24 },

    { name: "Thomas", age: 22 },

    { name: "Kate", age: 23 },

  ];

  

  students.sort((a, b) => a.age - b.age);

  console.log("After ascending sorting:", students);

  

  students.sort((a, b) => a.name.localeCompare(b.name));

  console.log("After alphabetically sorting:", students);

Output:

Output

After ascending sorting: [

  { name: 'Thomas', age: 22 },

  { name: 'Kate', age: 23 },

  { name: 'Yashraj', age: 24 }

]

After alphabetically sorting: [

  { name: 'Kate', age: 23 },

  { name: 'Thomas', age: 22 },

  { name: 'Yashraj', age: 24 }

]

Explanation:

In the previous illustration, we established a variable called students by employing the const keyword and allocated to it an array comprising objects. Each object includes a name and an age. By applying the technique of sorting objects, we arranged the array in ascending order based on age and displayed the outcome in the console.

Conclusion:

These JavaScript array functions enable us to efficiently sort arrays and manage data, whether we are working with basic values or intricate objects.

Frequently Asked Questions (FAQs):

  1. What is the method for incorporating elements into an array?

JavaScript offers a range of native array methods for appending elements to an array. The push method can be employed to insert an element at the conclusion of the array, while the unshift method is used to place an element at the start of the array.

  1. What are the methods to eliminate elements from an array?

The array can have elements removed through the use of the built-in methods pop and shift. Specifically, the pop method serves to eliminate the last element of the array, while the shift method is designed to remove the first element from the array.

  1. What approaches can we use to determine if a variable is an array?

The native method Array.isArray allows us to determine if a variable is an array. This method returns a Boolean value: it yields true if the variable is indeed an array, and false if it is not.

  1. How do we employ the forEach Method?

The forEach function offers a straightforward approach to iterate over every element in an array. It invokes a specified function for each item, supplying the item itself, its index within the array, and the complete array. This can be likened to having assistance to manage each element in a list sequentially. Importantly, this method does not generate a new array nor modify the existing one unless modifications are made within the function itself.

  1. How can we concatenate two arrays?

We can merge two arrays by employing the concat method.

Input Required

This code uses input(). Please provide values below: