ScriptS
Reactiflux5y ago
10 replies
Script

Script – 00-09 Jan 27

So I am trying to get value pairs from an array to be pushed into another array
This is my code:
function sockMerchant(n, ar) {
  ar.sort(function (a, b) {
    return a - b;
  });

  let groups = [];
  for (let i = 0, j = 1; i < ar.length; i += 2, j += 2) {
    if (ar[i] === ar[j]) {
      groups.push(ar.slice(i, i + 2));
    } else {
      i - 1;
      j - 1;
    }
  }

  return groups.length;
}

So this works fine for some values but when using
sockMerchant(20, [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5])
it returns 8 instead of 9.

I then discovered the problem is it skipping the index pairs that are not the same so I decided to add
i-1, j-1
so it goes back one index. But that didn't work
Any help?
Was this page helpful?