JavaScript array union

Ads
 

JavaScript array union

In this Tutorial we want to show you an example from array union in Java Script.

In this Tutorial we want to show you an example from array union in Java Script.

JavaScript array union

     

In this Tutorial we want to show you an example from array union in Java Script. The code contain a script that include a variable arr1 and arr2 instantiate an array object initialized with respectively specified element. The document. write print the respective element in an arr1 and arr2 object.

arr1.concat(arr2)  -  This method return you the combine element of arr1 and arr2 are assigned to var arr3.

array.array(unique) -  This method remove the duplicate element from combined array object elements.

The document. write print the list of array union element with no duplication in it.

JavaScript_Array_union.html

<html>
  <head>
  <title>JavaScript Array union</title>
  <h1>JavaScript Array union</h1>
  <hr></hr>
  <script  type="text/javascript">
  function unique(arrayName)
  {
  var newArray=new Array();
  label:for(var i=0; i<arrayName.length;i++ )
  {  
  for(var j=0; j<newArray.length;j++ )
  {
  if(newArray[j]==arrayName[i]) 
  continue label;
  }
  newArray[newArray.length] = arrayName[i];
  }
  return newArray;
  }
  </script>
  
  <script>
  var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0);
  var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5);
  document.write("<b>"+"First Array is :"+"</b>"+arr1+"<br>");
  document.write("<b>"+"Second Array is :"+"</b>"+arr2+"<br>");
  var arr3=arr1.concat(arr2);
  </script><hr></hr>
  <script>
  document.write("<b>"+"Array after union are:  "+"</b>"+unique(arr3));
  </script>
 </head>
  <body>
  </body>
</html>

Output of the program

Download source code

Ads

Ads