I have made a way to add the matches that are in array 2 with respect to array 1
array1 = [2, 4, 6];
array2 = [2, 4, 6, 2, 4, 6, 2];
let c1 = 0, c2 = 0, c3 = 0;
for (let i = 0; i < array2.length; i++) {
if (array1[0] === array2[i]){
c1 += 1;
}
if (array1[1] === array2[i]){
c2 += 1;
}
if (array1[2] === array2[i]){
c3 += 1;
}
}
console.log(c1, c2, c3) // 3 2 2
It works, but my doubt is if there is a more practical way, since I don't know how I would do it if there were more elements, it wouldn't be good to have c50, c70
, or do if (array1[50])
, etc. Thanks in advance
There are many ways to do it with different methods to traverse arrays, you can also use an object to store all the elements you have in the first array, first with a forEach we fill the object, and in the second forEach, we traverse the second array to count how many times the element is repeated inside our object, in this way we only have to go through the arrays 2 times and you save execution time
I would do it using 'map' and 'find'. This way I can get the same result as yours and it works regardless of the size of the array.
If you want the result to be an object, you have to use a
reduce
, like this: