JS计数两个数组之间的日期匹配


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

我想计算A中的元素在B中出现的次数(两个数组中都没有重复(

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

在其他两个arrA元素不匹配的情况下,这应该返回1的结果,而且确实如此。

当多个arrA日期与arrB中的一个元素匹配时,就会出现问题。然后,我仍然得到1

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

成功了。但出于某种原因,我最初写的并不是

您编写的是matchCounter =+ 1而不是matchCounter += 1

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

这个result应该等于3吗?

只需使用.filter()返回匹配项,回调就可以使用.includes()

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

诀窍是:

...
return matches.length;
};

返回匹配项的长度,而不是实际数组。

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

相关内容

  • 没有找到相关文章