Union of Array of Objects in JavaScript?

javascript difference between two arrays of objects
javascript array intersection
javascript array union
javascript intersect array of objects
javascript merge array of objects by key
merge javascript objects in array with same value
merge duplicate objects in array javascript
javascript array difference

So after searching the interwebz for a few hours I have not found the solution I am looking for.

I have two arrays that contain game objects with a lot of information inside. (e.g. title, slug, thumbnail, summary, genre, release date...).

The Array 1 is a collection of objects that match user's interests specified during the registration.

The Array 2 is a collection of objects that match purchased games of similar users. (Similar users are those that share common interests)

Problem: It is possible, and what is happening in my case, there are two identical games - the game in Array 1 is also in Array 2. In the first array the game is there because it matches user's interests. In the second array the game is there because a similar user has bought that game.

Question: Underscore.js has a nice little function union() http://underscorejs.org/#union that gives you a union of two arrays, but it does not work with an array of objects, only on primitive values. How could I make it work give me a union of array of objects?

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.

Union of Array of Objects in JavaScript?, which informally are collections of objects. We are not covering the same methods for Javascript Sets (Arrays and Sets are different data structures, you can  See the Pen JavaScript - Compute the union of two arrays - array-ex- 22 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: Write a JavaScript program to flatten a nested (any depth) array. Next: Write a JavaScript function to find the difference of two arrays.

You can do it using the underscore way:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

It just an improvment of the original function _.union(*arrays), adding an iteratee to work collection (array of object).

Here how to use it:

var result = collectionUnion(a, b, c, function (item) {
    return item.id;
});

The original function which is just working with array, looks like that:

_.union = function() {
  return _.uniq(flatten(arguments, true, true));
};

And in bonus a full example:

// collectionUnion(*arrays, iteratee)
function collectionUnion() {
    var args = Array.prototype.slice.call(arguments);
    var it = args.pop();

    return _.uniq(_.flatten(args, true), it);
}

var a = [{id: 0}, {id: 1}, {id: 2}];
var b = [{id: 2}, {id: 3}];
var c = [{id: 0}, {id: 1}, {id: 2}];

var result = collectionUnion(a, b, c, function (item) {
    return item.id;
});

console.log(result); // [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]

Array intersection, difference and union in ES6, A Set object can be created from an array (or any iterable object). If the array has duplicate elements, they are eliminated. // creating Set from an  The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Set (ES6/ES2015) will help you.

const info1 = {id: 1}
const info2 = {id: 2}
const info3 = {id: 3}

const array1 = [info1, info2]
const array2 = [info1, info3]

const union = [...new Set([...array1, ...array2])]

console.log(union)

Union of Arrays in JavaScript, Storing elements in JavaScript Object is going to remove the duplicate elements. At the end, push all element in a JavaScript array. Example: This example  Array Elements Can Be Objects. JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

jQuery has the method extend:

$.extend(true, object1, object2);

How to compute union of JavaScript arrays ?, How to Sort/Order keys in JavaScript objects ? The _.union() function is used to take n number of arrays and return a new array with the unique terms in all  We can represent a two-by-two table in JavaScript with a four-element array ([76, 9, 4, 1]). We could also use other representations, such as an array containing two two-element arrays ([[76, 9], [4, 1]]) or an object with property names like "11" and "01", but the flat array is simple and makes the expressions that access the table pleasantly short. We’ll interpret the indices to the array as two-bit binary numbers, where the leftmost (most significant) digit refers to the squirrel

Using underscore extend, you can do:

var objects = [{ bar : 1, nuts : 2} , {foo : 3, nuts : 4}]
_.extend.apply(this,objects)

If the list can be empty, make sure to append an empty object to it.

Underscore.js, That is, if a referenced object is modified, the changes are visible to both the new and original arrays. This includes elements of array arguments  Javascript Array of Objects If you have to store multiple objects in a single variable. then you can create an array of objects using arrays. let’s take an example of an array of objects.

Array.prototype.concat(), If array can't be split evenly, the final chunk will be the remaining elements. toPairs ; this method returns an object composed from key-value pairs . This method is like _.union except that it accepts iteratee which is invoked for each Despite multiple requests, the core-js maintainer has made it clear: any attempt to fix  By default, the JavaScript Array.sort function converts each element in the array that needs to be sorted into a string, and compares them in Unicode code point order. const foo = [9, 1, 4

template function, This method does not change the existing arrays, but returns a new array, containing the values of Return Value: An Array object, representing the joined array. The filter() method can be used to get intersection or difference of arrays. Duplicates can be eliminated by converting array to a Set object. Javascript Node.js PHP CSS UI / UX Bots Cloud Useful Resources

JavaScript Array concat() Method, _.union will always produce duplicates when passed arrays of objects. underscore's own isEqual function will tell you that the objects in question are e JS uses === or SameValueZero comparisons for many things. The concat () method is used to join two or more arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays. Browser Support. The numbers in the table specify the first browser version that fully supports the method. array1 .concat ( array2, array3, , arrayX) Parameter Values.

Comments
  • So what you need is a deep merge and extend? gist.github.com/1868955 stackoverflow.com/questions/7549574/… stackoverflow.com/questions/896043/…
  • phrogz.net/JS/ArraySetMath.js
  • I know this isn't your question, but have you considered using unique gameIds and using key:value object for your collections?
  • @cbayram I am using MongoDB. The reason for getting the game twice in this case is because the game matches user's interests query and I have a reference to Game collection inside User.purchasedGames array: purchasedGames: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Game' }}] which is another nested query. So I get separate results from 2 queries and then union them together.
  • Beat me to it. Nice implementation.
  • Hmm no luck getting it to work. Returns undefined. gist.github.com/4049901
  • Yeah, that's unsurprising when I forgot to return a value. :) Editing.
  • Nice. You could speed it up by having the outer loop stop at arr1.length and have the inner loop start at arr1.length (assuming we know that array 1 only has unique values and array 2 only has unique values). @TwilightPonyInc. - implementing are_games_same() is up to you depending on the structure of the objects, perhaps something like return g1.gameID === g2.gameID;.
  • you need to add j -= 1; after splicing. gist.github.com/dandybreath/85aa931c979f20d639f0
  • In the collection union (last bonus a full example) i will use: _.uniqBy(_.flatten(args, true), 'prop-id') lodash.com/docs/4.17.4#uniqBy
  • When using TypeScript and you don't want to turn on --downLevelIteration you can do const union = [...Array.from(new Set([...array1, ...array2]))]
  • So does underscore.js, but I was looking for a union operation. Extend from what I understand is for merging two objects. I want to eliminate an object entirely if it's already in the array. I guess you could use extend(), it just wasn't the first thing that came to my mind.