Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove non common items between two arrays javascript

I have a function to remove non common elements between two arrays in javascript but the issue is my code reduces some items in the array and increases some. Below is my code

function canFormPairs(cleanSocks, dirtySocks) {
  let compared = [];
  cleanSocks.forEach(item => {
    dirtySocks.forEach(dItem => {
      if (item == dItem) {
        compared.push(item);
      }
    });
  });
  return compared;
}
console.log(canFormPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));

The above code gives

[ 1, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 5, 5 ]

Instead of the desired result of

[1, 1, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7]

When sorted

Please what is the issue with this code

like image 442
diagold Avatar asked Dec 29 '25 04:12

diagold


1 Answers

Your current logic pushes the item for every unique index match between the two arrays. For example, with 7, 7 gets matched at index 3 (first array) and index 3 (second array), so it gets pushed once. Then, the next match is with index 3 (first array) and index 7 (second array). There are no more index matches other than 3-3 and 3-7, so only two 7 (values) get pushed.

I'd consider making a Set from both arrays, then combining both arrays and using .filter to remove elements not in both sets, and then sort the array:

function canFormPairs(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  return [...a, ...b]
    .filter(item => setA.has(item) && setB.has(item))
    .sort((a, b) => a - b);
}
console.log(canFormPairs([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));
like image 148
CertainPerformance Avatar answered Dec 31 '25 18:12

CertainPerformance