Mutator Methods are methods that change the array objects. For example Unshift(), Shift(), Push(), Pop(), Reverse(), Sort() and Splice().
In my previous article, I already explained the Unshift(), Shift(), Push(), Pop() methods. So, please refer to them.
Sort(): This method, as the name suggests, will sort the elements of an array in increasing (ascending) order by default.
Reverse(): This method will reverse the functioning of the sort() method. In other words, it changes the sorting pattern to descending (decreasing) order.
Example
- < script type = "text/javascript" >
- var myArray = ["Harry", "Tom", "Jerry", "Mike"];
- myArray.sort();
- document.write("The Sorted List in Ascending Order is: " + myArray + "<br/>");
- var myArray = ["Harry", "Tom", "Jerry", "Mike"];
- myArray.sort().reverse();
- document.write("The Sorted List in Descending Order is: " + myArray + "<br/>");
- < /script>
Now, if we change the elements with numeric values, it will not sort because it changes those values to a string and then sorts them. But, as we know, the numeric values cannot be sorted if they are strings.
So, we use the parameters in the sort function. The parameter of a sort function is also a function defined by the user.
Example
- < script type = "text/javascript" >
- var myArray = [10, 5, 6, 8, 23, 11];
- myArray.sort(function(a, b)
{
- return a - b
- });
- document.write("The Sorted List in Ascending Order is: " + myArray + "<br/>");
- var myArray = [10, 5, 6, 8, 23, 11];
- myArray.sort(function(a, b)
{
- return a - b
- }).reverse();
- document.write("The Sorted List in Descending Order is: " + myArray + "<br/>");
- < /script>
The function used above will check the first two values, in other words "10" and "5" as "a" and "b" in the function of the sort() method and subtract them and checks:
- If it is a positive value, then a > b.
- If it is a negative value, then a < b.
- If it is 0, then a = b.
On the basis of this criteria, it will swap the values and move forward. This process continues until all the elements are sorted.
Splice(): This method will add or remove elements from an array.
Syntax
- array.splice(index_location, no_of_values_to_be_deleted, new_items_to_add(optional));
Example to add elements
- var myArray = [1, 2, 5];
- myArray.splice(2, 0, 3, 4);
- document.write("After addition of the values, the elements of array are: " + myArray + "<br/>");
The preceding code adds 3 and 4 to the index location 2 and 0 is the delete count. That means we didn't want to delete any value from the array.
Example to delete elements
- var myArray = [1, 2, 3, 4, 5];
- myArray.splice(2, 2);
- document.write("After deletion of the values, the elements of array are: " + myArray);
The preceding code deletes 2 values at the index position 2.
For any queries, please leave a comment below.