Thursday, April 14, 2011

Method for Array operations: concat() and sort():

 
concat() : Joins two arrays and returns a new array.
Sort() :Sorts the elements of an array.

<script language="javascript">

Arr1=new Array(2,1,4,3) ;
Arr2=new Array(6,8,9,7) ;

document.write("<h2>First Array Arr1</h2>");
for(i=0;i<Arr1.length;i++)
document.write(Arr1[i]+"<br/>");

document.write("<h2>First Array Arr2</h2>");
for(i=0;i<Arr2.length;i++)
document.write(Arr2[i]+"<br/>");

Arr3=Arr1.concat(Arr2); //user for concat two array
document.write("<h2>First Array Arr1 after concat</h2>");
for(i=0;i<Arr3.length;i++)
document.write(Arr3[i]+"<br/>");

Arr3.sort();//user for sorting
document.write("<h2>First Array Arr1 after sort()</h2>");
for(i=0;i<Arr3.length;i++)
document.write(Arr3[i]+"<br/>");


</script>

Join:
join()  The string conversions of all array elements are joined into one string.

<script language="javascript">

Arr1=new Array("RED","YELLOW","GREEN") ;
MYVAR=Arr1.join();
document.write(MYVAR);


</script>

push() and pop():
push() : Add  elements to the end of an array and returns the new length of the array. This method changes the length of the array.
pop():Removes the last element from an array.

<script language="javascript">

Arr1=new Array("RED","YELLOW","GREEN") ;
document.write("<h3>Elements of array before push()</h3>");
for(i=0;i<Arr1.length;i++)
{
document.write(Arr1[i]+"<br/>");
}

Arr1.push("BLUE","WHITE","BLACK");
document.write("<h3>Elements of array after push()</h3>");
for(i=0;i<Arr1.length;i++)
{
document.write(Arr1[i]+"<br/>");
}
document.write("<h3>Elements of array after pop() 3 times</h3>");
for(i=0;i<=2;i++)
{
Arr1.pop();
}
for(i=0;i<Arr1.length;i++)
{
document.write(Arr1[i]+"<br/>");
}

</script>
reverse(): the first array element becomes the last and the last becomes the first.

<script language="javascript">

Arr1=new Array("RED","YELLOW","GREEN","BLUE","WHITE","BLACK") ;
document.write("<h2>Element of Array Before reverse()</h2><br/>");
for(i=0;i<Arr1.length;i++)
{
document.write(Arr1[i]+"<br/>");
}
Arr1.reverse();
document.write("<h2>Element of Array After reverse()</h2><br/>");
for(i=0;i<Arr1.length;i++)
{
document.write(Arr1[i]+"<br/>");
}

</script>

No comments:

Post a Comment