technology logo
technology logo

Javascript CodeART

share link

by lakharashubham623 dot icon Updated: Dec 27, 2022

Guide Kit Guide Kit  

DSA: union of two sorted arrays

<script>
// JavaScript program to find union of
// two sorted arrays


	/* Function prints union of arr1[] and arr2[]
	m is the number of elements in arr1[]
	n is the number of elements in arr2[] */
	function printUnion( arr1, arr2, m, n)
	{
		var i = 0, j = 0;
		while (i < m && j < n) {
			if (arr1[i] < arr2[j])
				document.write(arr1[i++] + " ");
			else if (arr2[j] < arr1[i])
				document.write(arr2[j++] + " ");
			else {
				document.write(arr2[j++] + " ");
				i++;
			}
		}


		/* Print remaining elements of
		the larger array */
		while (i < m)
			document.write(arr1[i++] + " ");
		while (j < n)
			document.write(arr2[j++] + " ");


		return 0;
	}


		var arr1 = [ 1, 2, 4, 5, 6 ];
		var arr2 = [ 2, 3, 5, 7 ];
		var m = arr1.length;
		var n = arr2.length;
		printUnion(arr1, arr2, m, n);
		
// this code is contributed by shivanisinghss2110
</script>


DSA: union of two sorted arrays


<script>

// javascript program to find union of two

// sorted arrays (Handling Duplicates)


function UnionArray(arr1 , arr2) {

// Taking max element present in either array

var m = arr1[arr1.length - 1];

var n = arr2[arr2.length - 1];


var ans = 0;


if (m > n) {

ans = m;

} else

ans = n;


// Finding elements from 1st array

// (non duplicates only). Using

// another array for storing union

// elements of both arrays

// Assuming max element present

// in array is not more than 10^7

var newtable = Array(ans+1).fill(0);


// First element is always

// present in final answer

document.write(arr1[0] + " ");


// Incrementing the First element's count

// in it's corresponding index in newtable

newtable[arr1[0]]+=1;


// Starting traversing the first

// array from 1st index till last

for (var i = 1; i < arr1.length; i++) {

// Checking whether current element

// is not equal to it's previous element

if (arr1[i] != arr1[i - 1]) {

document.write(arr1[i] + " ");

newtable[arr1[i]]+= 1;

}

}


// Finding only non common

// elements from 2nd array

for (var j = 0; j < arr2.length; j++) {

// By checking whether it's already

// present in newtable or not

if (newtable[arr2[j]] == 0) {

document.write(arr2[j] + " ");

++newtable[arr2[j]];

}

}

}


// Driver Code

var arr1 = [ 1, 2, 2, 2, 3 ];

var arr2 = [ 2, 3, 4, 5 ];


UnionArray(arr1, arr2);


// This code is contributed by gauravrajput1

</script>