Javascript Array Methods Explained
Working with Arrays is easier thanks to these array methods
Table of contents
- 1. Changing elements in an array
- 2. Find the length of an array
- 3. Join arrays
- 4. Check if an element exists in the Array
- 5. Convert array to string
- 6. Add elements into an array
- 7. Remove elements from the start of an array
- 8. Remove items from the end of an array
- 9. Slice array items
- 10. Remove and replace items in the array
- 11. Copy an array
- 12. Sort and Array
- 13. Reverse an array
- 14.Find the max and minimum values in an array
- Conclusion
Arrays are javascript data types that can store multiple values. Arrays simplify how data is stored by storing many values in a single variable. Here are some characteristics that distinguish arrays from other data types:
- Arrays are identified with their square brackets
[]
- Can Store different types of data types including strings, numbers, booleans, objects e.t.c.
Arrays are ordered and indexed from zero
0
Arrays are simple/one-dimensional (has only one level) or complex/multidimensional (nests one or more arrays)
- Arrays are mutable or modifiable meaning their values can be manipulated or changed using various methods.
- Array values can be accessed using the bracket notation
[]
In this article, I compile some popular inbuilt array methods used to manipulate data in arrays.
Permalink1. Changing elements in an array
Since arrays are ordered from zero [0] onwards, their values are accessed using indexes. This means you can add or remove elements easily by referencing their indexes. Like this;
const countries = ["Kenya" , "Uganda","Tanzania" ]
countries[1]='Morocco'
console.log(countries ) //returns ["Kenya" , "Morroco", "Tanzania"]
Permalink2. Find the length of an array
Use the length()
method to find out the size of the array
const countries = ["Kenya" , "Uganda","Tanzania" ]
console.log(countries.length) // -> 3 is the size of the array
Permalink3. Join arrays
Use the concat()
method to join two arrays together like this;
const firstList = [1, 2, 3]
const secondList = [4, 5, 6]
const newList = firstList.concat(secondList)
console.log(newList) //[1,2,3,4,5,6]
Permalink4. Check if an element exists in the Array
Use the indexOf()
to check whether an item exists in an array. If it does exist, it returns the index else it returns -1.
Let's use our list of countries again
const countries = ["Kenya", "Uganda","Tanzania" ]
countries.indexOf('Tanzania') //returns 2
countries.indexOf('Rwanda') //t=returns -1
Permalink5. Convert array to string
Use the toString()
method to change an array into a string.
Let's use our list of countries
const countries = ["Kenya" , "Uganda", "Tanzania" ]
console.log(countries.toString()) // ( Kenya,Uganda,Tanzania)
Alternatively, you can use the join()
method to specify how elements should appear on the string.
console.log(countries.join()) // KenyaUgandaTanzania -bundled together
console.log(countries.join('')) //KenyaUgandaTanzania-joined in one string
console.log(countries.join(' ')) //Kenya Uganda Tanzania-separate strings in a string
console.log(countries.join(', ')) //Kenya,Uganda,Tanzania-separated by commas
console.log(countries.join(' # ')) //Kenya# Uganda# Tanzania-separated by hashtags
Permalink6. Add elements into an array
Add items to the end of an array using the push method.
const countries = ["Kenya", "Uganda", "Tanzania" ]
countries.push("Somalia")
//returns
const countries=["Kenya", "Uganda", "Tanzania","Somalia" ]
You can choose to create a new array with extra items like this;
const countries=["Kenya", "Uganda", "Tanzania"]
let newCountries=countries.push("Ukraine")
//returns
newCountries=["Kenya", "Uganda", "Tanzania","Ukraine"]
Permalink7. Remove elements from the start of an array
shift() is similar to pop() , the only difference is it removes the first element of the array. This shifts all the other elements to a lower index.
const countries=["Kenya", "Uganda", "Tanzania"]
countries.shift()
console.log(countries) //returns ["Uganda", "Tanzania" ]
Notice, that the first element has been removed.
The unshift()
method does the opposite. unshift() will add items to the beginning of an array, changing the index of the other elements to a higher index.
Permalink8. Remove items from the end of an array
Use the pop()
method to remove elements from the end of an array.
const countries=["Kenya", "Uganda", "Tanzania"]
countries.pop()
console.log(countries) //returns ["Kenya", "Uganda"]
Notice Tanzania has been removed from the array
Permalink9. Slice array items
The slice()
method is used to extract elements from an array to create a new array. It takes two parameters, the start index and the end index(this position is however not picked but rather the previous one before it)
Like this;
const countries = ["Kenya", "Uganda", "Tanzania","Somalia" ]
let newCountries=countries.slice(1,3)
console.log(newCountries) // returns ["Uganda","Tanzania"]
] Notice that the 2nd index was extracted yet the 3rd index had been specified.
Permalink10. Remove and replace items in the array
Use the splice()
method to remove and replace items at any index in an array.Not just the start or end of an array as the
shift()
and
pop()
The splice method takes 3 parameters where to add or remove an item, how many items to be removed, and what items to add to the array
Clear an array ;
const countries = ["Kenya", "Uganda", "Tanzania","Somalia" ]
countries.splice()
console.log(countries) //returns empty list []
Remove an item at a specified index.
Here it takes two parameters the index of items to be removed and the number of items to be removed.
const countries = ["Kenya", "Uganda", "Tanzania","Somalia" ]
countries.splice(1,1)
console.log(countries) //returns [ "Kenya", "Tanzania","Somalia"]
Add items at a specific index
const countries = ["Kenya", "Uganda", "Tanzania","Somalia" ]
countries.splice(2,0,"Peru","Austria")
console.log(countries) //returns ["Kenya", "Uganda", "Peru","Austria","Tanzania","Somalia" ]
Permalink11. Copy an array
The spread operator ...
allows us to duplicate an array to make another array like this;
const countries = ["Kenya", "Uganda", "Tanzania"]
const newCountries =[...countries]
console.log(newCountries)
// returns [["Kenya", "Uganda", "Tanzania" ],["Kenya", "Uganda", "Tanzania" ]]
The spread operator can join two arrays together.
join arrays
const countries = ["Kenya", "Uganda", "Tanzania"]
const newCountries=["China", "Yugoslavia",...countries ,"Djibouti"]
console.log(newCountries)
//returns ["China", "Yugoslavia", "Kenya", "Uganda", "Tanzania","Djibouti"]
Permalink12. Sort and Array
The sort()
method arranges an array alphabetically
const countries = ["Kenya", "Uganda", "Tanzania"]
countrie.sort()
console.log( countries ) //returns ["Kenya", "Tanzania","Uganda" ]
Notice Tanzania moves to index one since it comes before Uganda on the alphabet.
Permalink13. Reverse an array
The reverse()
method changes the sequence in a given array, such that the first element becomes the last and the last becomes the first.
You can use it to sort an array in descending order:
const countries = ["Kenya", "Tanzania","Uganda" ]
countries.reverse()
console.log(countries) //returns ["Uganda", "Tanzania","Kenya"]
Permalink14.Find the max and minimum values in an array
There are many ways to find the maximum and minimum of elements in an array. Using the spread operator ...
is what I found to be the easiest.
Find maximum
const array1 = [1, 3, 2];
console.log(Math.max(...array1)); //returns 3
Find minimum
const array1 = [2, 3, 1];
console.log(Math.min(...array1)); //returns 1
You can use javascript Math methods to manipulate data in arrays. See the links in the references section below.
PermalinkConclusion
There you go. You now have a clear explanation of the 13 most used javascript methods. There are many more listed in the references provided below. Check them out and keep using them in your projects. Feel free to correct and suggest additions. Happy coding!
References