如何比较2个数组并检查jQuery / Javascript中的任何项是否相同 [英] How to compare 2 arrays and check if any item is the same in jQuery/Javascript

查看:88
本文介绍了如何比较2个数组并检查jQuery / Javascript中的任何项是否相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这两个数组,如果两个数组中都有任何相同的元素,我试图抛出一个警告,任何机构都有这方面的经验吗?



So I have these two arrays and I am trying to throw an alert if both arrays have any of the same element in them, any body have any experience with this?

var selectedFacils = [];
var selectedExcludeFacils = [];
$("#selectFacilParams_chosen").find(".search-choice").each(function () {
    var elem = jQuery(this).text();
    selectedFacils.push(elem);
});
$("#selectFacilParamsExclude_chosen").find(".search-choice").each(function () {
    var elem = jQuery(this).text();
    selectedExcludeFacils.push(elem);
});

推荐答案

#selectFacilParams_chosen).find( 。search-choice)。each(function(){
var elem = jQuery( this )。text();
selectedFacils.push (elem);
});
("#selectFacilParams_chosen").find(".search-choice").each(function () { var elem = jQuery(this).text(); selectedFacils.push(elem); });


#selectFacilParamsExclude_chosen )。find( 。search-c hoice)。each(function(){
var elem = jQuery( this )文本();
selectedExcludeFacils.push(elem);
});
("#selectFacilParamsExclude_chosen").find(".search-choice").each(function () { var elem = jQuery(this).text(); selectedExcludeFacils.push(elem); });


感谢您的澄清。这意味着您需要执行N * M比较,其中N和M是两个数组的长度。在两个嵌套循环中执行。



这很简单,你的数组键是连续的整数,你知道大小。在Javascript中,任何数组都是具有任何键的关联容器。如果这是问题,您可以使用 Object.keys 并按键迭代。请参阅:

https:// developer .mozilla.org / zh-CN / docs / Web / JavaScript / Reference / Global_Objects / Object / keys [ ^ ]。



为了更好的替代方案,分析如何最终拥有两个具有重复对象的不同数组,并在将对象添加到数组时首先考虑防止这种情况。



-SA
Thank you for the clarification. It means that you need to perform N * M comparisons, where N and M are lengths of the two arrays. Do it in two nested loops.

This is simple is your array keys are consecutive integers and you know the sizes. In Javascript, any array is an associative container with any keys. If this is the concern, you can use Object.keys and iterate by keys. Please see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys[^].

For better alternative, analyze how you end up having two different arrays with duplicate objects and think at preventing this situation in first place, when you add objects to the array.

—SA


这篇关于如何比较2个数组并检查jQuery / Javascript中的任何项是否相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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