I have written a function in Javascript to eliminate non-common elements between two arrays. However, I am facing an issue where my code decreases the frequency of some items while increasing others. Here is the code snippet:
function findCommonElements(arr1, arr2) {
let common = [];
arr1.forEach(item => {
arr2.forEach(element => {
if (item == element) {
common.push(item);
}
});
});
return common;
}
console.log(findCommonElements([1, 5, 6, 7, 5, 6, 5, 56], [1, 5, 6, 7, 8, 5, 6, 7, 8, 78]));
The output from the code above is:
[ 1, 5, 5, 6, 6, 7, 7, 5, 5, 6, 6, 5, 5 ]
Instead of the expected result:
[1, 1, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7]
After sorting
Can someone help me identify what is wrong with this code?