Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return only the number of matching pair values in array?

Say I found a box of loose shoes (all the same kind) at a garage sale, and I've created an array with each individual shoe listed by shoe size.

I want to display the number of paired values of shoe sizes 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:

10,10
10,10
20,20

And 3 remaining values that don't have a matching pair-value (20,30,50).

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]))
like image 553
Diasline Avatar asked Sep 07 '19 21:09

Diasline


Video Answer


1 Answers

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.delete(arr[i])) {
      count++;
    } else {
      set.add(arr[i])
    }
  }

  return count;
}
console.log(pairNumbers([10, 10, 10, 10, 20, 20, 20, 30, 50])) // 3
like image 142
Matt Aft Avatar answered Oct 20 '22 05:10

Matt Aft