skip to Main Content
<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>

result 2023-04-062023-04-07
how to result like this 2023-04-06, 2023-04-07

2

Answers


  1. You can achive your results by using this

    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']
    

    if you want a string instead, you can join the array

    found.join() // '2023-04-06,2023-04-07'
    
    Login or Signup to reply.
  2. The simplest way is to just filter, to keep values that are in both arrays

    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(", ");

    If you find yourself with super long arrays, you can benefit from Sets, which offer constant time lookup for if a value is contained. For small arrays, it really doesn’t matter and you might even find the creation of the Set making the Set approach slower.

    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(", ");
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search