Javascript: Find pairs within an array in a for loop

/* I want to count the pairs of the same array so that it returns 3 (10 and 10, 20 and 20 & 30 and 30) There is an error and the if statement but I don’t know what it is, can anyone help please. */

  const sockMerchant = (arr) => {
        var count = 0;
             for(var i = 0; i < arr.length; ++i){
                 if(arr[i] == 2)
             count++;
             } console.log(count);
             }
              const pairs = [10, 20, 20, 10, 10, 30, 50, 10, 20];     
          sockMerchant((pairs));

All you are currently doing is checking to see if the current item in the list equals 2. The task requires more complex logic than that. You’ll have to check if the element before is equal to the current element (a little hint).

1 Like

my code is not working either and I could not figure out why

const sockMerchant = (arr) => {
const count = 0;
sort(arr, arr + n);
for(var i = 0; i < arr.length; ++i){
if(arr[i] == arr[i] +1)
count++;
i = i + 2; }
else {
i++;
} return count;
}
const pairs = [10, 20, 20, 10, 10, 30, 50, 10, 20];
sockMerchant((pairs));

There are a few issues here.

  • Presumably, count will be used to count something, and need to be incremented (re-assigned), so declaring it with const is probably not the best approach.
  • Regarding: sort(arr, arr + n). Even if Array.sort() could be called this way (it can’t), arr is the array that was passed to the function, n is not defined, but if it were, what would arr + n be? You can review how to use Array.sort() here.
  • Regarding: if(arr[i] == arr[i] + 1) This can never evaluate to truthy. For example, when i is 0, arr[i] will be 10, so arr[i] + 1 will be 11 (10 + 1). You probably meant to add 1 to the index, i.
  • You’ll also have issues trying to manually change the value of i (you will skip some of the indices). You could use a while loop instead, or (a bit unconventional) eliminate incrementing i in the for loop statement: for (let i = 0; i < arr.length;) {, and manually increment i as you are currently.
  • With the lack of indentation, it’s harder to see, but you have issues with missing curly braces as well.
1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.