Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
Check how many times a value in an array appears in another array

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report

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);

about 4 years ago · Juan Pablo Isaza Report

0

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);

 
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!