JavaScript中对象数组的联合? [英] Union of Array of Objects in JavaScript?

查看:109
本文介绍了JavaScript中对象数组的联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在搜索interwebz几个小时之后我找不到我想要的解决方案。

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

我有两个包含很多游戏对象的数组里面的信息。 (例如标题,slu ,,缩略图,摘要,类型,发布日期......)。

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

数组1 是一组符合用户在注册时指定的兴趣的对象。

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

数组2 是一个集合匹配购买类似用户的游戏的对象。 (类似用户是那些有共同兴趣的用户)

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

问题:有可能,在我的情况下发生了什么,有两个完全相同游戏 - 阵列1中的游戏也在阵列2中。在第一个阵列中,游戏就在那里,因为它符合用户的兴趣。在第二个阵列中,游戏就在那里,因为类似的用户购买了该游戏。

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.

问题:Underscore.js有一个很好的小功能联盟() http://underscorejs.org/#union ,它提供了两个数组的并集,但它确实不适用于对象数组,仅适用于原始值。我怎么能让它工作给我一个对象数组的联合?

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);

请参阅 JavaScript中的对象比较,用于各种对象比较实现。

Refer to Object comparison in JavaScript for various object comparison implementations.

这篇关于JavaScript中对象数组的联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆