繁体   English   中英

在数组中查找匹配的元素

[英]Find matching elements in an array

我有一个像这样的数组{A1,B5,C6,A2,B7,C4}; 我想遍历数组并找到匹配的元素,然后在该匹配中进行一些操作。 上面数组中的匹配项是A1和A2,B5和B7,最后是C6和C4。

以下是我到目前为止所做的事情:

var arr = {A1,B5,C6,A2,B7,C4};
for (i=0; i < arr.length/2; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably
{
for (j=i+1; j < arr.length; j++)
       {
         if(arr[i].charAt(0) == arr[j].charAt(0))
           {
             j=arr.length; //This is done to end the inner loop
             Do something;
             //if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this.
           }
       }
 }

您将需要首先对数组进行排序,以使查找匹配对更加容易。 这是修改代码的一种方法。

 var arr = ['A1','B5','C6','A2','B7','C4'] arr.sort(); console.log("Sorted array : " + arr); for (i=0; i < arr.length -1; i++) // Only running till length/2 since there is always another match hence don't need to run through all the length probably { if(arr[i].charAt(0) == arr[i+1].charAt(0)) { j=arr.length; //This is done to end the inner loop console.log("Match found : " + arr[i].charAt(0)); //if the matching element is found, ideally the i loop should ignore this record. I don't know how to do this. } } 

您可以创建一个具有所有匹配项的对象,如下所示:

 var arr = ['A1','B5','C6','A2','B7','C4']; var setsOfMatches = {}; arr.forEach(function(currentItem) { var firstLetter = [currentItem.charAt(0)]; if (setsOfMatches[firstLetter]) { //If we have a set for this letter already setsOfMatches[firstLetter].push(currentItem); //Add this item to it } else { setsOfMatches[firstLetter] = [currentItem]; //Create the set } }); //console.log(setsOfMatches); //{ // A:["A1","A2"], // B:["B5","B7"], // C:["C6","C4"] //} //Iterate through the sets of matches for (var set in setsOfMatches) { console.log("Set " + set + ": " + setsOfMatches[set]); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM