Intro
Over my last two blogs we went over how to create and manipulate arrays through techniques such as push()
, pop()
, slice()
, and splice()
. On this final blog on arrays, we will look at how to combine arrays and how to iterate through arrays.
How to Combine Arrays
One cool feature of the spread operator, that we didn't go over in the last blog, is how to combine arrays. The syntax to combine arrays is very simple:
let myArray = ['dog','cat','horse'];
let myNewArray = ['bird',...myArray,'pig','cow']
console.log(myNewArray) [ 'bird', 'dog', 'cat', 'horse', 'pig', 'cow' ]
Using the spread operator we easily combined the two arrays.
Find the Index of an Element
Once we start writing long arrays it may be difficult to remember the index location of a certain element. Luckily Javascript has a built in method called indexOf()
that can find the element easily. Here is the syntax for indexOf()
using our previous example:
let myArray = ['dog','cat','horse'];
let myNewArray = ['bird',...myArray,'pig','cow']
myNewArray.indexOf('dog') // 1
myNewArray.indexOf('pig') // 4
myNewArray.indexOf('snake') // -1 Will return -1 if element can't be found
As you can see indexOf()
can be incredible useful for both finding if an element exists and the index it is located at.
Iterate Through an Array
Very often when working with arrays we may need to iterate through each item. Using a for
loop we can do this easily:
let myArr = ['dog', 'cat', 'whale','snake'];
for(let i = 0; i < myArr.length; i++){
console.log(`These are the animals in my zoo ${myArr[i]}`)
}
// 'These are the animals in my zoo dog'
// 'These are the animals in my zoo cat'
// 'These are the animals in my zoo whale'
// 'These are the animals in my zoo snake'
As you can see by using a for
loop we were able to iterate through every element in our array and add them to our custom sentence.
Conclusion
After finishing this third blog you are fully prepared to create and manipulate arrays, one of the more commonly used data structure. In our next blog we will look at another common data structure, objects.
Top comments (0)