在数组中查找匹配的元素

时间:2017-04-28 14:53:05

标签: javascript arrays

我有一个像这样的数组{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.
           }
       }
 }

2 个答案:

答案 0 :(得分:0)

您需要先对数组进行排序,以便更容易找到匹配的对。以下是修改代码的一种方法。

&#13;
&#13;
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.
           }
 }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

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]);
}