with - javascript vs java




How can I return only the number of paired values in array? (3)

I want to display the number of paired values in the array. For example, I have this array:

[10,10,10,10,20,20,20,30,50]

I would like to display 3 because we have 3 pairs of numbers. How can I do this?

function pairNumber(arr) {
  var sorted_arr = arr.sort();
  var i;
  var results = [];
  for (i = 0; i < sorted_arr.length; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
      results.push(sorted_arr[i]);
    }

  }
  return results.length;
}
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))


Here is another approach using a Set :

function pairNumbers(arr) {
  let count = 0;
  const set = new Set();

  for (let i = 0; i < arr.length; i++) {
    if (set.has(arr[i])) {
      count++;
      set.delete(arr[i])
    } else {
      set.add(arr[i])
    }
  }

  return count;
}
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3


I'd reduce into an object, counting up the number of occurrences of each number. Then reduce again on the Object.values of the object to count up the number of pairs, adding Math.floor(count / 2) to the accumulator on each iteration:

function pairNumber(arr) {
  const itemCounts = arr.reduce((a, item) => {
    a[item] = (a[item] || 0) + 1;
    return a;
  }, {});
  return Object.values(itemCounts)
    .reduce((pairsSoFar, count) => pairsSoFar + Math.floor(count / 2), 0);
}
console.log(pairNumber([10, 10, 10, 10, 20, 20, 20, 30, 50]))

Probably better to avoid .sort if possible - that increases the computational complexity from O(n) (minimum) to O(n log n) .


Many thanks to all guys that help me understand more how to solve this issue. After sturdying the answers in the post I come up with my own solution.

Thanks to you I understand I should increment i at the end of if to prevent a repetitive comparison.

function pairNumbers(arr) {
const sorted_arr = arr.sort();
const results = [];
for (let i = 0; i < sorted_arr.length; i++) {
if (sorted_arr[i] == sorted_arr[i + 1]) {
results.push(sorted_arr[i]);
i = i + 1; 
}

}
return results.length;
}
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3




javascript