How to use the push() method In Javascript
- Here, all elements are stored in a JavaScript object.
- Storing elements in JavaScript Object is going to remove the duplicate elements.
- In the end, push all elements in a JavaScript array by using push() method.
Example: This example implements the above approach.
let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
function computeUnion(a, b) {
let object = {};
for (let i = a.length - 1; i >= 0; --i)
object[a[i]] = a[i];
for (let i = b.length - 1; i >= 0; --i)
object[b[i]] = b[i];
let ret = [];
for (let i in object) {
if (object.hasOwnProperty(i))
ret.push(object[i]);
}
return ret;
}
console.log(computeUnion(A, B));
Output
[ 1, 2, 4, 5, 6, 7, 9 ]
How to compute union of JavaScript arrays ?
Given two arrays containing array elements and the task is to compute the union of both arrays with the help of JavaScript.
These are the methods to solve this problem which are discussed below:
Table of Content
- Using the spread operator and set
- Using the push() method
- Using filter() and concat() Method
- Using Underscore.js _.union() Function
- Using reduce() and includes()