paint-brush
Array Manipulation: Understanding JavaScript Array Methodsby@deewyne
6,139 reads
6,139 reads

Array Manipulation: Understanding JavaScript Array Methods

by Daniel YerimahJanuary 9th, 2023
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

JavaScript arrays are data types that can store a collection of elements. These elements can be of any data type, including numbers, strings, and objects. Arrays in JavaScript are dynamic, meaning that you can add or remove elements from them after they have been created. In this tutorial we will look into all the JavaScript array methods and how they are applied in practice.
featured image - Array Manipulation: Understanding JavaScript Array Methods
Daniel Yerimah HackerNoon profile picture

What are Arrays in JavaScript? JavaScript arrays are data types that can store a collection of elements. These elements can be of any data type, including numbers, strings, and objects. Arrays in JavaScript are dynamic, meaning that you can add or remove elements from them after they have been created.


In this tutorial, we will look into all the JavaScript array methods and how they are applied in practice.


Types of Array methods

There are several methods for manipulating JavaScript arrays. Some of these methods are:

1. concat()

This method is used to merge two or more arrays. It does not modify the original arrays, but instead returns a new array that contains the elements of the original arrays.


Here is an example of how `concat()` can be used in JavaScript:


const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];

const mergedArray = array1.concat(array2, array3);
// mergedArray is [1, 2, 3, 4, 5, 6, 7, 8, 9]


In the example above, array1, array2, and array3 are all merged into a single array called `mergedArray`. `concat()` takes any number of arrays as arguments and returns a new array that contains all the elements of the original arrays.


You can also use `concat()` to merge arrays with non-array values. For example:


const array1 = [1, 2, 3];
const mergedArray = array1.concat(4, 5, 6);
// mergedArray is [1, 2, 3, 4, 5, 6]


In this case, the values 4, 5, and 6 are added to the end of array1 to create the `mergedArray`.


Note that `concat()` does not modify the original arrays. Instead, it creates a new array that contains the elements of the original arrays. If you want to modify an array in place, you can use the `push()` method instead.


2.  join()

This method is used to join all the elements of an array into a string. It takes an optional separator parameter, which specifies the character to be used to separate the elements of the array in the resulting string. If no separator is provided, the elements are separated by a comma.


Here is an example of how `join()` can be used in JavaScript:


const array = ['apple', 'banana', 'orange'];
const fruitString = array.join();
// fruitString is 'apple,banana,orange'

const array = [1, 2, 3];
const numberString = array.join('-');
// numberString is '1-2-3'


In the first example, the elements of the array are joined into a single string with a comma as the separator. In the second example, the elements of the array are joined into a single string with a hyphen as the separator.


You can also use `join()` on an array of arrays to create a string of nested arrays:


const array = [[1, 2], [3, 4], [5, 6]];
const nestedArrayString = array.join('-');
// nestedArrayString is '1,2-3,4-5,6'


Note that `join()` does not modify the original array. It creates a new string that contains the elements of the array. If you want to modify the array in place, you can use the `splice()` method instead.


3.  pop()

This method is used to remove the last element of an array and return it. It modifies the original array.


Here is an example of how `pop()` can be used in JavaScript:


const array = [1, 2, 3, 4, 5];
const lastElement = array.pop();
// lastElement is 5
// array is [1, 2, 3, 4]


In this example, the `pop()` method removes the last element (5) from the array and assigns it to the `lastElement` variable. The array is then modified to remove the last element, leaving it with a length of 4.


You can also use `pop()` in combination with other array methods, such as `push()` to add elements to the end of the array:


const array = [1, 2, 3];
array.push(4);
array.pop();
// array is [1, 2, 3]


In this example, the `push()` method adds the element 4 to the end of the array, and then the `pop()` method removes it again, leaving the array unchanged.


Note that if the array is empty, `pop()` returns undefined.


const array = []; 
const element = array.pop(); 
// element is undefined


4.  push()

This method is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.


Here is an example of how push() can be used in JavaScript:


const array = [1, 2, 3];
const newLength = array.push(4, 5, 6);
// array is [1, 2, 3, 4, 5, 6]
// newLength is 6


In this example, the push() method adds the elements 4, 5, and 6 to the end of the array and returns the new length of the array (6). The array is then modified to include these elements.


You can also use push() to add an array of elements to the end of another array:


const array = [1, 2, 3];
const newLength = array.push([4, 5, 6]);
// array is [1, 2, 3, [4, 5, 6]]
// newLength is 4


In this example, the push() method adds the array [4, 5, 6] as a single element to the end of the array, and returns the new length of the array (4).


Note that push() modifies the original array. If you want to create a new array that includes the elements of the original array, you can use the concat() method instead.

5. shift()

This method is used to remove the first element of an array and return it. It modifies the original array.


Here is an example of how shift() can be used in JavaScript:


const array = [1, 2, 3, 4, 5];
const firstElement = array.shift();
// firstElement is 1
// array is [2, 3, 4, 5]


In this example, the shift() method removes the first element (1) from the array and assigns it to the firstElement variable. The array is then modified to remove the first element, leaving it with a length of 4.


You can also use shift() in combination with other array methods, such as unshift() to add elements to the beginning of the array:


const array = [1, 2, 3];
array.unshift(0);
array.shift();
// array is [1, 2, 3]


In this example, the unshift() method adds the element 0 to the beginning of the array, and then the shift() method removes it again, leaving the array unchanged.


Note that if the array is empty, shift() returns undefined.


const array = []; 

const element = array.shift(); 

// element is undefined


6. unshift()

This method is used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.


Here is an example of how unshift() can be used in JavaScript:


const array = [1, 2, 3];
const newLength = array.unshift(4, 5, 6);
// array is [4, 5, 6, 1, 2, 3]
// newLength is 6


In this example, the unshift() method adds the elements 4, 5, and 6 to the beginning of the array and returns the new length of the array (6). The array is then modified to include these elements at the beginning.


You can also use unshift() to add an array of elements to the beginning of another array:


const array = [1, 2, 3];
const newLength = array.unshift([4, 5, 6]);
// array is [[4, 5, 6], 1, 2, 3]
// newLength is 4


In this example, the unshift() method adds the array [4, 5, 6] as a single element to the beginning of the array, and returns the new length of the array (4).


Note that unshift() modifies the original array. If you want to create a new array that includes the elements of the original array, you can use the concat() method instead.


7. slice()

This method is used to extract a section of an array and return a new array. It does not modify the original array. The slice method takes two optional parameters: a start index and an end index.

If the start index is not specified, it defaults to the start of the array. If the end index is not specified, it defaults to the end of the array.


Here is an example of how slice() can be used in JavaScript:


const array = [1, 2, 3, 4, 5];
const slice = array.slice(1, 3);
// slice is [2, 3]
// array is [1, 2, 3, 4, 5] (unchanged)


In this example, the slice() method extracts the elements at indices 1 and 2 (2 and 3) from the array and returns them in a new array called slice. The original array is not modified.


You can also use slice() with a single argument, which indicates the start index:


const array = [1, 2, 3, 4, 5];
const slice = array.slice(2);
// slice is [3, 4, 5]
// array is [1, 2, 3, 4, 5] (unchanged)


In this case, the slice() method extracts all the elements of the array starting from the index 2 (inclusive) to the end of the array.


You can also use negative indices with slice(), which indicates the position of the element relative to the end of the array:


const array = [1, 2, 3, 4, 5];
const slice = array.slice(-2);
// slice is [4, 5]
// array is [1, 2, 3, 4, 5] (unchanged)


In this case, the slice() method extracts the last two elements of the array.

Note that if the start index is greater than the end index, slice() returns an empty array.


8. splice()

The splice() method in JavaScript is used to add or remove elements from an array and return the removed elements as a new array. It modifies the original array.


The splice() method takes at least two arguments: a start index and a delete count. The start index is the index at which the splice begins, and the delete count is the number of elements to be removed.


Here is an example of how splice() can be used to remove elements from an array:


const array = [1, 2, 3, 4, 5];
const removedElements = array.splice(1, 2);
// removedElements is [2, 3]
// array is [1, 4, 5]


In this example, the splice() method removes the elements at indices 1 and 2 (2 and 3) from the array and returns them in a new array called removedElements. The original array is modified to remove these elements.


You can also use splice() to add elements to an array:


const array = [1, 2, 3];
const removedElements = array.splice(1, 0, 4, 5, 6);
// removedElements is []
// array is [1, 4, 5, 6, 2, 3]


In this case, the splice() method adds the elements 4, 5, and 6 to the array at the index 1, and the delete count is 0, so no elements are removed. The original array is modified to include these elements.


You can also use splice() to both add and remove elements at the same time:


const array = [1, 2, 3, 4, 5];
const removedElements = array.splice(1, 2, 6, 7);
// removedElements is [2, 3]
// array is [1, 6, 7, 4, 5]


In this example, the splice() method removes the elements at indices 1 and 2 (2 and 3) from the array and adds the elements 6 and 7 at the same indices. The original array is modified to include the added elements and remove the removed elements.


Note that if the start index is greater than the length of the array, splice() does not add or remove any elements, but simply returns an empty array.


9. reverse()

This method is used to reverse the order of the elements in an array. It modifies the original array.


Here is an example of how reverse() can be used in JavaScript:


const array = [1, 2, 3, 4, 5];
array.reverse();
// array is [5, 4, 3, 2, 1]


In this example, the reverse() method reverses the order of the elements in the array, so that the first element becomes the last and the last element becomes the first.


You can also use reverse() on an array of objects:


const array = [{id: 1}, {id: 2}, {id: 3}];
array.reverse(); // array is [{id: 3}, {id: 2}, {id: 1}]


In this case, the reverse() method reverses the order of the objects in the array.


Note that reverse() modifies the original array. If you want to create a new array that is the reverse of the original array, you can use the slice() and reverse() methods together:


const array = [1, 2, 3, 4, 5];
const reversedArray = array.slice().reverse();
// reversedArray is [5, 4, 3, 2, 1]
// array is [1, 2, 3, 4, 5] (unchanged)


In this example, the slice() method creates a shallow copy of the array, and the reverse() method reverses the elements in the copy, leaving the original array unchanged.


10. sort()

This method is used to sort the elements of an array in place. It can take an optional compare function as a parameter, which allows you to specify a custom sorting algorithm. If no compare function is provided, the elements are sorted in ascending order according to their Unicode code points.


Here is an example of how sort() can be used in JavaScript:


const array = [5, 2, 4, 1, 3];
array.sort();
// array is [1, 2, 3, 4, 5]


In this example, the sort() method sorts the elements of the array in ascending order.


You can also use sort() with a compare function as its argument to specify a custom sort order:


const array = [{name: 'John'}, {name: 'Jane'}, {name: 'Bob'}];
array.sort((a, b) => a.name.localeCompare(b.name));
// array is [{name: 'Bob'}, {name: 'Jane'}, {name: 'John'}]


In this case, the sort() method sorts the objects in the array based on their name properties using the localeCompare() method. Note that sort() modifies the original array.


Also by default, sort() converts the elements of the array to strings and sorts them based on their Unicode point values. This can lead to unexpected results for non-string values. For example:


const array = [10, 5, 8, 1, 7];
array.sort();
// array is [1, 10, 5, 7, 8]


In this case, the sort() method converts the numbers to strings before sorting them, so the resulting array is not in numerical order. To sort the array in numerical order, you can use a compare function as the argument to sort():


const array = [10, 5, 8, 1, 7];
array.sort((a, b) => a - b);
// array is [1, 5, 7, 8, 10]


If you want to sort the elements of an array in descending order, you can use the following compare function as the argument to sort():


const array = [5, 2, 4, 1, 3];
array.sort((a, b) => b - a);
// array is [5, 4, 3, 2, 1]


Conclusion

These are just a few of the many methods available for working with arrays in JavaScript. I hope this helps! Let me know if you have any other questions.