一个for循环,用于比较两个寻找匹配值的数组

我有两个数组,我需要互相检查,如果他们已达到每个数组中的两个项目实际上彼此相同的点,然后在某处附加一些html。

以下是我一直在尝试的一些代码:

var daysArray = ["1", "2", "3", "4", "5"]; var courseHwork = ["4", "8", "15", "16", "23", "42"]; 

所以在上面的数组中只有一个匹配值,即:“4”

这是下一部分:

 for (var i = 0; i < courseHwork.length; i++) { //in my actual code courseHwork contains several objects, each of which //has a duedate property, so here I want to see if this part of the duedate //property is equal to any position in the daysArray array. if (courseHwork[i].duedate.substring(8,10) === daysArray[i]) { //here I mean to select an element of this class that contains a string //that is equal to that of the matching positions in both arrays. then //once found it should take the title property from one of the objects in the //courseHwork array and append it there. $('.fc-day-number:contains("'+daysArray[i]+'")').append("
"+courseHwork[i].title+"

"); } }

如果事情按计划运行,它将找到一个包含字符串“4”的div,并从courseHwork数组中的匹配对象附加该属性“title”。

注意:我的实际daysArray将数字覆盖为字符串“1” – “31”,并且courseHwork对象数组是动态填充的,因此它可以包含任意数量的对象,但是没有对象的属性值超过“31”。找到子字符串。

* 问题:我如何遍历两个数组,每次在两个数组之间找到匹配值时,会发现一个html元素也包含完全相同的值,然后附加一些内容? *

这是我提出的想法:

 var daysArray = ["1", "2", "3", "4", "5", "12"]; var courseHwork = ["4", "8", "15", "16", "23", "42", "12"]; for (var i = 0; i < courseHwork.length; i++) { for (var j = 0; j < daysArray.length; j++) { if (courseHwork[i] == daysArray[j]) { $('div:contains("'+daysArray[j]+'")').append("
"+courseHwork[i]+" - appended
"); } } }

你可以在这里找到它: http : //jsfiddle.net/4cqCE/2/

那么,检查一下你想要的是什么。 首先,它在2个数组中查找SAME值,如果找到它,它会向div中包含“4”的div。 那是你要的吗?

下面是一个带有2个相同值的示例,其中包含2个div,每个div包含一个值。 http://jsfiddle.net/4cqCE/3/

你可以这样做:

 var daysArray = ["1", "2", "3", "4", "5"]; var courseHwork = ["4", "8", "15", "16", "23", "42"]; var arr = daysArray.concat(courseHwork); var sorted_arr = arr.sort(); var results = []; for (var i = 0; i < arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } console.log(results); 

你可以在这里运行代码: http : //jsfiddle.net/WtEwJ/2/

这将导致新的数组results只包含重复的项目。

我认为你应该首先创建一个数组交集 ,然后迭代结果来做你的事情……

嗨使用lodash或下划线你可以很容易地交叉两个数组。

_.intersection([2, 1], [2, 3]);

结果是[2]。

Lodash文件: https ://lodash.com/docs/4.17.2#intersection