I am trying to see how many times a value in one array appears in another. This was one thing I but it didn't work.
arr1 = [1, 2, 3, 4, 5];
arr2 = [1, 7, 8, 9, 10];
count = 0;
for (x in arr2){
for (y in arr1){
if (x == y){
count +=1;
}
}
}
console.log(count);
Another thing i tried was this.
(arr1.some((val)=>{return arr2.includes(val);} ))
It checks if at least one value matches but i wasn't sure on how to implement a count for it.
My goal is to see how many times a value from arr2 appears in arr1. It should return 1 in this case.
You could use Array.prototype.reduce in combination with Array.prototype.filter in order to get an Object of repeated values
const arr1 = [1, 2, 3, 4, 5, 1, 1, 1, 9, 9]; // Repeated values
const arr2 = [1, 7, 8, 9, 10]; // Unique values
const appearances = (arrUnique, arrRepeated) => arrUnique.reduce((ob, valUnique) => {
ob[valUnique] = arrRepeated.filter(v => valUnique === v).length;
return ob;
}, {});
console.log(appearances(arr2, arr1)); // {value: counts, ...}
console.log(appearances(arr2, arr1)[1]); // 4
which will return:
{
"1": 4, // repeats 4 times
"7": 0,
"8": 0,
"9": 2, // repeats 2 times
"10": 0
}
You could take an object from the counting values, then iterate the second array and count only wanted values.
const
array1 = [1, 2, 3, 4, 5],
array2 = [1, 7, 8, 9, 10],
result = array1.reduce(
(r, v) => (v in r && r[v]++, r),
Object.fromEntries(array2.map(v => [v, 0]))
);
console.log(result);
x and y will be the indexes of the loops when using this syntax. So get what you are after you could do it like this.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 7, 8, 9, 10];
count = 0;
for (x in arr2){
for (y in arr1){
if (arr2[x] === arr1[y]){
count +=1;
}
}
}
console.log(count);