Getting a union of two arrays in JavaScript
If you don't need to keep the order, and consider 45
and "45"
to be the same:
function union_arrays (x, y) { var obj = {}; for (var i = x.length-1; i >= 0; -- i) obj[x[i]] = x[i]; for (var i = y.length-1; i >= 0; -- i) obj[y[i]] = y[i]; var res = [] for (var k in obj) { if (obj.hasOwnProperty(k)) // <-- optional res.push(obj[k]); } return res;}
console.log(union_arrays([34,35,45,48,49], [44,55]));
How to get the union of two arrays
var a = [1,2,3];
var b = [2,3,5];
//Concat both arrays [1,2,3,2,3,5]
var result = a.concat(b).filter(function(value, index, self) { //array unique
return self.indexOf(value) === index;
});
console.log(result); //[1, 2, 3, 5];
How can I uniquely union two array of objects?
Concat and use Array#filter with a helper object to remove duplicates:
var array1 = [{"a":1,"b":"first"},{"a":2,"b":"second"}];
var array2 = [{"a":3,"b":"third"},{"a":1,"b":"fourth"}];
var result = array2.concat(array1).filter(function(o) { return this[o.a] ? false : this[o.a] = true;}, {});
console.log(result);
How to merge two arrays in JavaScript and de-duplicate items
To just merge the arrays (without removing duplicates)
ES5 version use Array.concat
:
var array1 = ["Vijendra", "Singh"];
var array2 = ["Singh", "Shakya"];
array1 = array1.concat(array2);
console.log(array1);
Union of Array of Objects in JavaScript and es6?
You could implement your own pretty easily. In this case, we make the function generic, so that it can take arrays of any data type(s) and union them using the comparator function provided.
// arr1 and arr2 are arrays of any length; equalityFunc is a function which
// can compare two items and return true if they're equal and false otherwise
function arrayUnion(arr1, arr2, equalityFunc) {
var union = arr1.concat(arr2);
for (var i = 0; i < union.length; i++) {
for (var j = i+1; j < union.length; j++) {
if (equalityFunc(union[i], union[j])) {
union.splice(j, 1);
j--;
}
}
}
return union;
}
function areGamesEqual(g1, g2) {
return g1.title === g2.title;
}
// Function call example
arrayUnion(arr1, arr2, areGamesEqual);
Refer to Object comparison in JavaScript for various object comparison implementations. JavaScript: How to get the union of 2-3 sets without any library/package functions
If you mean ES6 sets then you can do it simply:
function union(...sets) {
return new Set([].concat(...sets.map(set => [...set])));
}
Then union(new Set([1, 2, 3]), new Set([3, 4, 5]));
will return Set(4) {1, 2, 3, 4, 5}
If you need it to be done with ES5:
function unique(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
function union() {
var result = [];
for (var i = 0; i < arguments.length; i++) {
result = result.concat(arguments[i]);
}
return unique(result);
}
And usage will beunion([1, 2, 3], [3, 4, 5], [4, 5, 6]); // => [1, 2, 3, 4, 5, 6]
Union between three arrays
Just another solution keeping the original function signature provided by the OP:
function union(...arrays) {
return Array.from(new Set([...arrays].flat()));
}
console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]));
Or, even shorter (but less read friendly):return [...(new Set([...arrays].flat()))];
Explanation:
Array.from
takes an Iterable as an argument, this will create a new array from the original one.[...arrays]
spreads the arrays (argument) into a new, single, one (So it becomes an array of arrays) ->[5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]
becomes:[[5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]]
.flat
flattens the array, making that an array of values rather than ar array of arrays of values -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat ->[[5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]]
becomes[5, 10, 15, 15, 88, 1, 5, 7, 100, 15, 10, 1, 5]
new Set
removes duplicates from the array and returns an Iterable https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set. ->[5, 10, 15, 15, 88, 1, 5, 7, 100, 15, 10, 1, 5]
becomes a Set instance (an Iterable) without the duplicates. Array.from then converts the Set (Iterable) to a regular array. Further infos here: How to convert Set to Array?
Array.flat
is currently an experimental feature (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat). Solution without using flat below:function union(...arrays) {
return Array.from(new Set([].concat.apply([],[...arrays])));
}
console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]));
Explanation (only differences from above):- Instead of .flat, we apply to
Array.concat
our original array, so that it will flatten it passing a new array as itsthis
and providing our array as the argument:[].concat.apply([],[...arrays])
Snippet without .flat
: http://jsfiddle.net/briosheje/y03osape/4/
How to calculate intersection of multiple arrays in JavaScript? And what does [equals: function] mean?
I wrote a helper function for this:
function intersection() {
var result = [];
var lists;
if(arguments.length === 1) {
lists = arguments[0];
} else {
lists = arguments;
}
for(var i = 0; i < lists.length; i++) {
var currentList = lists[i];
for(var y = 0; y < currentList.length; y++) {
var currentValue = currentList[y];
if(result.indexOf(currentValue) === -1) {
var existsInAll = true;
for(var x = 0; x < lists.length; x++) {
if(lists[x].indexOf(currentValue) === -1) {
existsInAll = false;
break;
}
}
if(existsInAll) {
result.push(currentValue);
}
}
}
}
return result;
}
Use it like this:intersection(array1, array2, array3, array4); //["Lorem"]
Or like this:intersection([array1, array2, array3, array4]); //["Lorem"]
Full code hereUPDATE 1
A slightly smaller implementation here using filter
How to get the difference between two arrays in JavaScript?
This answer was written in 2009, so it is a bit outdated, also it's rather educational for understanding the problem. Best solution I'd use today would be
let difference = arr1.filter(x => !arr2.includes(x));
(credits to other author here)I assume you are comparing a normal array. If not, you need to change the for loop to a for .. in loop.
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
Related Topics
What Is the Point of Void Operator in JavaScript
How to Convert Numbers Between Different Bases in JavaScript
Can Jquery Read/Write Cookies to a Browser
How to Pass a Flag to Gulp to Have It Run Tasks in Different Ways
JavaScript Switch VS. If...Else If...Else
How to Send Authorization Header with Axios
Does Use of Anonymous Functions Affect Performance
Alternative or Polyfill for Array.From on the Internet Explorer
How to Use Jquery to Style /Parts/ of All Instances of a Specific Word
Javascript: Cancel/Stop Image Requests
Onclick Event Binding in React.Js
How to Bind to the Change Event of a Textarea in Jquery
Do Browsers Parse JavaScript on Every Page Load
Angular 2 Karma Test 'Component-Name' Is Not a Known Element