Javascript array operations
So, what is an array? An array is a special kind of variable that can contain more than one value at a time. In simple it can be referred to as a collection of variables.
var fruits= [“apple”, “orange”, “mango”];
In the above example, we can see an array of strings. Javascript can handle complex arrays. Like, arrays of objects. Let’s see an example.
In the above example, there are two objects in the ‘cars’ array. You can access an object element like you can access a normal element in an array. fruits[0] will give you the first fruit object. Now we will discuss some useful array operations.
- If you need an object to insert in the first position of our fruits array. use
Array.unshift()
. Example-
2. Now, maybe you need a new object to be added to the end of the array. For that, you should use Array.push()
. Example-
3. This one is interesting. Maybe you need to add an object in the middle. Now, what you will do? Don’t worry, you should use Array.splice()
. But it is important for other things. This method can also be used to remove elements.
Now if you want to add an element in position 2. Watch out closely for this example-
4. The pop()
method removes the last element from an array. It is very simple, just type fruits.pop()
, and the last element will be removed.
5. Find an object in an array by its value using Array.find()
method. Example-
the fr variable will contain the object whose name property is mango.
6. The above Array.find()
method will return you only one matching element. Now, what if you need all the elements with the name mango. For this, you should use Array.filter()
method.
7. I think you are familiar with looping in structural mapping. To remind you, I am talking about for loop, while loop etc. There is a build-in method Array.map()
by which you can do this iterating very easily and do your desired operations on individual elements like you can do with for loop.
8. Now, maybe you need to add a property to each object of that fruits array what will you do. You will use Array.forEach()
method. Example-
Now, I will shortly discuss two more methods.
9. If you want to merge two arrays, use Array.concat()
10. The last method we are going to discuss today is Array.slice()
. Now, this is a handy method. If you want to slice out a piece of an array into a new array. Try this-
This example slices out a part of an array starting from array element 3 (“Apple”).
If you have read this far and implemented the examples, then you deserve a high five. These methods will be very useful if you want to learn javascript.