Array Functions

What are different array functions or methods in javascript?
How can we sort the elements in javascript array?

Explanation

Array Methods :
Array has the following predefined methods.
toString()
join()
reverse()
sort()

Method: toString() :
This method is used to convert the array elements in to a string. The string will have each element in the array separated by comma(,).

Example:


<script language="javascript">
var varname = new Array();
varname[0] = "testing to string 1";
varname[1] = "testing to string 2";
document.write("toString -- "+varname.toString());
</script>

Result:



Method: join() :
This method is used to join the elements in the array separated by a separator. This function is much similar to toString method. Here we can specify the delimiter or separator that comes instead of comma.

Example:


<script language="javascript">
var aarray = new Array();
aarray[0] = "element 1";
aarray[1] = "element 2";
var xx = aarray.join(" +++ ");
document.write("join() -- "+xx);
</script>

Result:



Method: sort() :
This method is used for sorting elements in the array. The values will be sorted in a dictionary order.

Example:


<script language="javascript">
var sorting = new Array();
sorting[0] = "b for balloon";
sorting[1] = "d for donkey";
sorting[2] = "a for apple";
sorting.sort();
document.write("sort function -- "+sorting.toString());
</script>

Result:




Ask Questions

Ask Question