Union of Two Arrays in Javascript
Union of Two Arrays in Javascript
Union of Two Arrays in Javascript is the today topic of discussion in this tutorial.
Algorithm of Union of Two Arrays in Javascript
- Initialize Two Array: ( Array1 and Array2 with values)
- Initialize result [ ] as empty.
- Initialize and obj { } as empty.
- Copy all elements of Array1 to obj.
- Copy all elements of Array2 to obj.
- x is present in obj, then copy x into result.
- Return result.
- Display result
Union of Two Arrays in Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<!DOCTYPE html> <html> <head> // head start <title > Programs In Java Script </title> //title of the Program </head> //head close <body> //body start <h2> //heading start <b> Union Of Two Array</b> //heading text </h2> //heading close <br> // next line <p id="demo"></p> //paragrapgh <br> // next line <script> //java Script Start function union() //function of union { var array1=[1, 2, 3,4]; //array 1 var array2=[100, 2, 1, 10]; ///array 2 var result = []; ///variable result var obj = {}; /// variable obj for (var i = 0; i < array1.length; i++) //foor loop { obj[array1[i]] = true; } for (var j = 0; j < array2.length; j++) //foor loop { obj[array2[j]] = true; } for(const x in obj) { result.push(x); } return result; //return result } document.write(union()); //display result </script> </body> </html> |
Output
Union of two array
1, 2, 3, 4, 10, 100