Saturday, May 11, 2024
138
rated 0 times [  142] [ 4]  / answers: 1 / hits: 21256  / 12 Years ago, sat, november 10, 2012, 12:00:00

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?


More From » ecmascript-6

 Answers
15

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.


[#82072] Thursday, November 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patriciakiarrac

Total Points: 532
Total Questions: 100
Total Answers: 89

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
patriciakiarrac questions
;