gpt4 book ai didi

javascript - Lodash JS - 在普通 Javascript 中模拟 '_.intersectionWith'?

转载 作者:行者123 更新时间:2023-11-30 00:07:07 24 4
gpt4 key购买 nike

如何为 LodashJs 库的 '_.intersectionWith' 方法编写等效的简单 Javascript 方法

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.intersectionWith(objects, others, _.isEqual);

Output: [{ 'x': 1, 'y': 2 }]

我希望它也适用于字符串数组。有没有 O(n^2) 次迭代的方法?

感谢您的帮助。

最佳答案

这是一个功能强大的纯 JS 实现 _.intersectionWith :

var objects = [{'x':1,'y':2},{'x':2,'y':1}],
others = [{'x':1,'y':1},{'x':1,'y':2}];

function isEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}

function intersectionWith(firstArray) {
var otherArrays = Array.prototype.slice.call(arguments, 1, -1),
comparator = arguments[arguments.length - 1];
return firstArray.filter(function(a) {
return otherArrays.every(function(arr) {
return arr.some(function(b) {
return comparator(a, b);
});
});
});
}

console.log(intersectionWith(objects, others, isEqual));

在 ES6 中,如果您允许比较器作为第一个参数,则可以更短。

function intersectionWith() {
var [comp, first, ...others] = [...arguments];
return first.filter(a => others.every(arr => arr.some(b => comp(a, b))));
}

关于javascript - Lodash JS - 在普通 Javascript 中模拟 '_.intersectionWith'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38109032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com