<script>
var array1 = ['2023-04-05','2023-04-06','2023-04-07','2023-04-08']; //array1
var array2 = ['2023-04-06','2023-04-07']; //array2
found1 = array1.find((val, index) => { //find the date in array1
return array2.includes(val);
});
$('.show').html(found1);
</script>
结果2023-04-062023-04-07怎么这样的结果2023-04-06,2023-04-07
最简单的方法就是过滤,保留两个数组中的值
const array1 = ['2023-04-05','2023-04-06','2023-04-07','2023-04-08']; //array1
const array2 = ['2023-04-06','2023-04-07']; //array2
const found1 = array1.filter((val) => array2.includes(val)); //find the date in array1
console.log(found1);
// display however you want
document.body.innerText = found1.join(", ");
如果您发现自己使用超长数组,您可以从Set
s中受益,它为包含值提供恒定时间查找。对于小型数组,这真的无关紧要,您甚至可能会发现Set
的创建使Set
方法变慢。
const array1 = ['2023-04-05','2023-04-06','2023-04-07','2023-04-08']; //array1
const array2 = new Set(['2023-04-06','2023-04-07']); //array2
const found1 = array1.filter((val) => array2.has(val)); //find the date in array1
console.log(found1);
// display however you want
document.body.innerText = found1.join(", ");
您可以通过使用
实现您的结果var array1 = ['2023-04-05','2023-04-06','2023-04-07','2023-04-08']; //array1
var array2 = ['2023-04-06','2023-04-07']; //array2
const found = []
array1.forEach(date => {
if (array2.includes(date)) {
found.push(date)
}
})
console.log(found) // ['2023-04-06', '2023-04-07']
如果你想要一个字符串,你可以加入数组
found.join() // '2023-04-06,2023-04-07'