Today I will just talk about six important array methods (did you notice that I was not calling them functions, rather calling them methods, that’s because when a function is belongs to an object we like to call them methods, for now you can think it something of a synonym of function), these methods are push(), pop(), unshift(), shift(), splice(), indexOf().
Let’s create a simple array: Array courtesy w3schools, couldn’t think of better elements above fruits!
var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits);
Let’s now add a new element at the the end of the array. I will also print the output on the console every times I add or remove the element. So on your browser open the inspect window to see the output.
Let’s now remove this added element.
Now let’s use unshift() & shift() methods:
Using unshift() method we just have added a new element at the beginning of the array, shift() method on the other hand will remove it from the beginning of the array.
Now what about if we want to remove or add an element from or to the middle of the array! Well we can use splice() method (there actually a movie on that name and actually good!), this method comes in different flavours. Consider this example, where I will be using this method to add new elements in the array.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits); fruits.splice(2, 0, "Lemon", "Kiwi"); console.log(fruits);
On this particular case, splice() method will add two new elements on the place of Apple, first parameter tells the position in array( remember array starts from 0), second parameter tells how many elements to be removed ( this case 0 element) and third and forth parameters are new elements to be added.
let’s now use splice() method to remove element.
var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits); fruits.splice(0, 1); // Removes the first element of fruits. console.log(fruits);
But what if you don’t know the index of the array element to be removed! In that case, one another helpful array method is indexOf() can come handy.
This indexOf() method can be used to search first matching element from the array. The indexOf() method returns the position of the first occurrence of a specified value in a string. This method returns -1 if the value to search for never occurs
So from the previous example if we want to find the index of Banana then we can do the following:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log(fruits); var itemIndex = fruits.indexOf("Banana"); console.log(itemIndex); fruits.splice(itemIndex, 1); console.log(fruits);
Well job is done, we have used indexOf() method to find the index of Banana and kept the index in a variable called itemIndex and then used this variable with splice() method to remove it. this way we can combine both the methods to make things more dynamic!
That’s all for this week, more important array methods to come, just keep en eye for the new post!