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