JavaScript 和 es6 中对象数组的联合?

新手上路,请多包涵

所以在 interwebz 上搜索了几个小时后,我还没有找到我正在寻找的解决方案。

我有两个包含游戏对象的数组,里面有很多信息。 (例如标题、别名、缩略图、摘要、流派、发布日期…)。

Array 1 是匹配用户在注册期间指定的兴趣的对象的集合。

Array 2 是一组匹配相似用户购买的游戏的对象。 (相似用户是指有共同兴趣的用户)

问题:有可能,在我的情况下,有两个相同的游戏 - 数组 1 中的游戏也在数组 2 中。在第一个数组中,游戏在那里,因为它符合用户的兴趣。在第二个数组中,游戏存在是因为类似的用户购买了该游戏。

问题:Underscore.js 有一个不错的小函数 union() http://underscorejs.org/#union 可以为您提供两个数组的并集,但它不适用于对象数组,只能用于原始值。我怎样才能让它工作给我一个对象数组的联合?

原文由 Sahat Yalkabov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 623
2 个回答

您可以很容易地实现自己的。在这种情况下,我们使该函数成为通用函数,以便它可以采用任何数据类型的数组并使用提供的比较器函数将它们合并。

 // 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 中的对象比较

原文由 Chris Hayes 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用下划线方式来做到这一点:

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

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

它只是对原始功能 _.union(*arrays) 的改进,将迭代器添加到工作集合(对象数组)中。

这里如何使用它:

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

仅使用数组的原始函数如下所示:

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

还有一个完整的例子:

 // 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 } ]

原文由 Arnaud Valensi 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题