Home > OS >  JS counting Date matches between 2 arrays
JS counting Date matches between 2 arrays

Time:03-23

const arrA = ['2022-03-01', '2022-03-02', '2022-03-03']
const arrB = ['2022-01-20', '2022-02-22', '2022-03-03' ...more ]

I wanna count how many times an element from A appears in B (there are no duplicates in either array)

let matchCounter = 0
arrA.forEach((date) => {
  if(arrB.includes(date)) matchCounter =  1
  if(!arrB.includes(date)) matchCounter = matchCounter
})

This should, in case the other two arrA elements don't match, return a result of 1, and it does.

The problem comes when more than one of the arrA dates match with an element from arrB. Then, I still get a 1

CodePudding user response:

arrA.forEach((date) => if(arrB.includes(date)) matchCounter   )

did the trick. But what I initially wrote does not for some reason

CodePudding user response:

You wrote matchCounter = 1 instead of matchCounter = 1.

CodePudding user response:

const arrA = ['2022-03-01', '2022-03-02', '2022-03-03']
const arrB = ['2022-01-20', '2022-02-22', '2022-03-03', '2022-03-03', '2022-03-02']
const result = arrA.reduce((a, c) => a   arrB.filter(i => i == c).length, 0);
console.log(result);

should this result equals 3?

CodePudding user response:

Simply use .filter() to return the matches and the callback can use .includes().

const matchCount = (arrA, arrB) => {
  const matches = arrA.filter(date => arrB.includes(date));
...

Here's the trick:

...
  return matches.length;
};

Return the length of matches not the actual array.

const arrA = ['2022-04-20', '2022-05-12', '2022-03-13'];

const arrB = ["2022-05-12", "2022-03-17", "2022-04-10", "2022-03-30", "2022-03-28", "2022-05-04", "2022-04-15", "2022-04-13", "2022-04-16", "2022-04-20"];

const matchCount = (array1, array2) => {
  const matches = array1.filter(str => array2.includes(str));
  return matches.length;
};

console.log(matchCount(arrA, arrB));

  • Related