Mastering JavaScript Array and it methods
Master the functional power of JavaScript arrays. From basic manipulation to advanced iteration, this deep dive breaks down the most essential methods for building lean, high-performance codebases. Learn to handle data structures with the same 'aesthetic precision' you apply to your UI.
Emmanuel Abanobi
Arrays are variables that can hold multiple values. In this article, I will be discussing JavaScript arrays and their methods.
const myArray = ["Nigeria", "USA", "Canada", "Benin"]
The code above is an example of how an array looks in JavaScript.
Congratulations, we just wrote our first array variable in JavaScript!
Why Arrays in JavaScript?
We use arrays in JavaScript in order to reduce the amount of repeated code in our program. Instead of saving each value in a separate variable, we can just put them into an array.
Now let's focus on how we can manipulate our array to get our desired outcome.
In JavaScript, there are several methods we can use in manipulating arrays. These are well-known as array methods. However, without these methods, we can't work with arrays effectively.
Array Methods
We have multiple array methods in JavaScript, and I will explain each of them in this article.
Array slice()
An array slice is used to select an element in an array and store it in a new array. However, the original array remains the same, unlike the pop and push methods.
Syntax: array.slice(first, end)
const myArray = ["Nigeria", "USA", "Canada", "Benin"]
const newArray = myArray.slice(0, 2)
console.log(newArray) // this returns ["Nigeria", "USA"]
Code Explanation:
In our code above, we created an array that we called myArray, then we used the slice method to select some elements in myArray, which were the first and second values in myArray elements. In JavaScript, if we are to target a value or element in an array, we use number type to get the index of the element we are targeting, which means an index of 0 is the first element in myArray and also index of 1 is the second element in myArray. As we all know, we do not count from an index of 1 in JavaScript; we start counting from an index of 0. In conclusion, we then saved the selected elements in a new variable called newArray.
Array splice()
The array splice method removes or adds elements in an array and returns the removed elements if any.
Syntax: array.splice(index, howmany, item1, ....., itemX)
const myArray = ["Nigeria", "USA", "Canada", "Benin"]
myArray.splice(3, 1, "Spain", "Zimbabwe")
console.log(myArray) // this returns ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
Code Explanation:
In our example above we created an array, then we used the splice method to start adding more countries at the index of 3. The 1 inside the splice method is the number of items we want to remove before adding our new countries. Lastly, we added the countries we wanted to add inside our array.
Array sort()
This method is used for sorting or organizing an array in a descending or ascending order.
Syntax: array.sort(compareFunction)
const myArray = ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
myArray.sort()
console.log(myArray) // this returns ["Canada", "Nigeria", "Spain", "USA", "Zimbabwe"]
//Example (sorting in ascending order)
const myArray = ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
myArray.sort()
console.log(myArray) // this returns ["Canada", "Nigeria", "Spain", "USA", "Zimbabwe"]
Example (sorting in descending order):
const myArray = ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
myArray.sort()
myArray.reverse()
console.log(myArray) // this returns ["Zimbabwe", "USA", "Spain", "Nigeria", "Canada"]
Code Explanation:
In the code above, we created an array of countries, then we used the sort method to organize the code alphabetically. For descending order, we combined sort() with reverse(). If you are sorting numbers, it targets the smallest to the biggest and vice versa, but if you are sorting strings, it targets the first letter to organize alphabetically.
Array shift() and unshift()
Now let's look into the shift and unshift methods. We can use the shift method to completely remove the first element in our array. We can store the value which was removed entirely from our original array in a new array variable, if necessary.
The unshift method is used to add elements at the beginning of the original array.
Syntax: array.shift() array.unshift(item1, item2, ..., itemX)
Example:
const myArray = ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
myArray.shift()
console.log(myArray) // this returns ["USA", "Canada", "Spain", "Zimbabwe"]
// Using the unshift method
myArray.unshift("Ethiopia")
console.log(myArray) // This returns ["Ethiopia", "USA", "Canada", "Spain", "Zimbabwe"]
Code Explanation:
Using the .shift and .unshift methods is very simple because we do not need to do any complex solution to get our desired outcome. We just have to use the .shift or the .unshift syntax on our array. The .unshift syntax added an element to the start of our original array and the .shift element removed the first element.
Array pop() and array push()
This array method plays almost a similar role as the shift and unshift methods. However, the array.pop() method removes the last element from an array, while the array.push() method can be used to add new elements to an array.
Syntax:
array.pop() array.push(item1, item2, ..., itemX)
Example:
const myArray = ["Nigeria", "USA", "Canada", "Spain", "Zimbabwe"]
myArray.pop()
console.log(myArray) // This returns ["Nigeria", "USA", "Canada", "Spain"]
// Using the push method
myArray.push("Ethiopia")
console.log(myArray) // This returns ["Nigeria", "USA", "Canada", "Spain", "Ethiopia"]
Array delete()
Array.delete() can be used to delete an element in an array, but I will advise you not to use this method because it leaves an undefined hole in your code. Instead, you can use the pop or shift method to delete an element in an array.
Syntax:
delete arrayindex
Example:
const myCities = ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala"]
delete myCities[0]
console.log(myCities) // This returns [empty, "Sacramento", "Tokyo", "Capetown", "Kampala"]
Array join()
Array join() joins all elements together that are separated by commas or any specific separators in an array.
Syntax:
array.join(separator)
Example:
const myCities = ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala"]
console.log(myCities.join('')) // this returns "LagosSacramentoTokyoCapetownKampala"
console.log(myCities.join(' - ')) // this returns "Lagos - Sacramento - Tokyo - Capetown - Kampala"
Array concat()
This method joins two or more arrays together. Moreover, it works just like the + operator.
Syntax: array1.concat(array2, array3, ..., arrayX)
Example:
const myCities1 = ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala"]
const myCities2 = ["Texas", "Addis Ababa", "Accra", "Cotonou"]
const newArray = myCities1.concat(myCities2)
console.log(newArray) // this returns ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala", "Texas", "Addis Ababa", "Accra", "Cotonou"]
Code Explanation:
In the code above, we created our first array "myCities1" and also created another array called "myCities2". We then called the concat method on myCities1 and added myCities2 to the parenthesis. This resulted in the first and second arrays joining together to form a new array.
Array toString()
Array toString() works on turning all the elements in an array into one string type.
Syntax:
array.toString()
Example: const myCities = "Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala" const newArray = myCities.toString() console.log(newArray) // This returns "Lagos,Sacramento,Tokyo,Capetown,Kampala"
Code Explanation:
We created an array in the code above. After that, we created a new variable called newArray, and then we assigned it to the original array "myCities" and called the toString() method on myCities. Finally, we logged newArray to our console and got our desired result.
Array length
The length method checks for the length of an array element and returns the actual number of elements in an array.
Syntax: array.length
Example:
const myCities = ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala"]
const arrayLength = myCities.length
console.log(arrayLength) // 5
Bonus example:
const myCities = ["Lagos", "Sacramento", "Tokyo", "Capetown", "Kampala"]
myCities.length = 3
console.log(myCities) // This returns ["Lagos", "Sacramento", "Tokyo"]
Code Explanation:
This is a very simple code. We started by creating a new array, afterward, we created a variable and assigned it to our original array "myCities" and called the length method. After that, we console logged the variable, which resulted in 5 because the length of our myCities array is 5.
In our second example, myCities.length returns "Lagos", "Sacramento", "Tokyo" because we assigned myCities.length to get the length of 3 elements.
Array flat()
Array flat methods are used to concatenate sub-arrays elements.
Syntax: array.flat()
Example:
const myArray = [[1,2], [3,4], [5,6]]
const newArray = myArray.flat()
console.log(newArray) // This returns [1,2,3,4,5,6]
Explanation:
The code above takes the nested array [[1,2], 3,4, 5,6] and transforms it into a single-dimensional array 1, 2, 3, 4, 5, 6 by flattening it using the flat() method.
Conclusion
We have come to the end of this article. I hope you understand all concepts that were explained in this article. As we all know, array methods are very great tools to use while manipulating arrays. In this article, we looked at the frequently used array methods.
Please note, there are more array methods in JavaScript that we didn't look into. You can read more on array methods here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array