简体   繁体   中英

Find matching elements in an array

I have an array like this {A1,B5,C6,A2,B7,C4}; I want to loop through the array and find the matching element and then do some manipulation in that match. The match in the above array is A1 and A2, B5 and B7 and finally C6 and C4.

Below is what I have done so far:

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.
           }
       }
 }

You will need to sort the array first to make it easier to find the matching pairs. Here is one way you can modify your code.

 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. } } 

You could create an object with all the matches, like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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