What is the best way to find common elements in two arrays?

I have two arrays and I am trying to compare them in order to find the matching values only.

For instance, both arrays contain the date 2023/03/07, which is the value that should be returned.

I haven't come across a solution for this yet. What would be the most efficient way to identify the similarities?

var array1 = ["2023/03/07", "2023/03/17", "2023/03/27"];
var array2 = [];
var startDate = "2023/03/05";
var endDate = "2023/03/15";
var dateMove = new Date(startDate);
var strDate = startDate;

while (strDate < endDate) {
  var strDate = dateMove.toISOString().slice(0, 10);
  array2.push(strDate);
  dateMove.setDate(dateMove.getDate() + 1);
}

found = array1.find((val, index) => {
  return array2.includes(val);
});

console.log(found);
// if value in array1 is equal to value in array2 then return match: 2023/03/07

Answer №1

The toISOString() method requires dashes (-) as the separator:

YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ

By replacing slashes with dashes in the array, startDate, and endDate variables, the code will function correctly:

var array1 = ["2023-03-07", "2023-03-17", "2023-03-27"];
var array2 = [];
var startDate = "2023-03-05";
var endDate = "2023-03-15";
var dateMove = new Date(startDate);
var strDate = startDate;

while (strDate < endDate) {
  var strDate = dateMove.toISOString().slice(0, 10);
  array2.push(strDate);
  dateMove.setDate(dateMove.getDate() + 1);
}

found = array1.find((val, index) => {
  return array2.includes(val);
});

console.log(found);

Answer №2

If there are multiple values found, your current code will not work as the result of find is being assigned to found. It's important to note that find returns the first result found. Refer to the documentation for more information.

To address this issue, update the code to use Array.filter instead:

found = array1.filter((val, index) => {
  return array2.includes(val);
});

In addition, I would like to highlight a helpful library called luxon, which simplifies working with dates:

var { DateTime, Interval } = require('luxon');

var array1 = ["2023-03-07", "2023-03-17", "2023-03-27"];
var startDate = "2023-03-05";
var endDate = "2023-03-15";

const interval = Interval.fromDateTimes(DateTime.fromISO(startDate), DateTime.fromISO(endDate));

var found = array1.filter(date => interval.contains(DateTime.fromISO(date)));

console.log(found);

If you prefer to maintain the input format using slashes instead of dashes, Luxon allows you to create DateTime objects using fromFormat.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to track keystrokes without the use of text input fields?

For various unimportant reasons, I need to use JavaScript to create links instead of using the anchor tag. I want the behavior to mimic the anchor tag, allowing users to open a link in a new tab when holding down the Ctrl key or in a new window when holdin ...

Modify the href value by matching it with the parent div attribute

I am working on an HTML project <div class="1" style="" title="NeedthisText TextIDontneed"> <div class="2> <div class="3"> <a target="_blank" href="/NeedToChange/DispForm.aspx?ID=1"></a> </div> </div> &l ...

The type of undefined cannot be assigned to the specified type

I am currently working on implementing a pie chart (donut series) in Angular. Below are my HTML, CSS, and TypeScript files. I am following this tutorial resource: Link to CodeSandBox - https://codesandbox.io/s/apx-donut-simple-8fnji?from-embed import ...

Find the position of the largest number in an array

Is there a way to retrieve the index of the highest value in an array similar to the one shown below? In the given array, the expected output would be '11'. Array ( [11] => 14 [10] => 9 [12] => 7 [13] => 7 [14] =& ...

encounter an error while attempting to interpret json

I'm currently encountering an issue while attempting to parse a JSON file. Instead of the expected value, I keep getting undefined. Specifically, I only want to retrieve the value associated with the key level1. [{ "id": 2, "name": "Peter", "pr ...

Struggling with obtaining react-modal in my React Component

Greetings to all React developers out there, especially the newbies like me. I am currently facing an issue with implementing react-modal in my React Component based on this example here. Unfortunately, I have encountered several errors that are proving di ...

Issue with inconsistent indentations in Pug template

Dealing with the Pug template engine has been a frustrating experience. Despite spending an entire day trying to figure it out, all I got was errors about inconsistent indentations. It's disheartening when my text ends up in the "our sponsor section" ...

Monitor MongoDB for expired document date fields

I'm currently working with MongoDB and MeteorJS, and I'm wondering if there is a way to observe the value of a specific field in a document. I know we can observe document updates, creations, and removals, but I am interested in monitoring a fiel ...

Can all the keys in an object be updated in an atomic manner? Is there a way to achieve this, similar to using splice for an array?

Currently in the process of implementing undo/redo functionality for a project I am working on. To ensure a smooth undo/redo feature, changes must be atomic to avoid stepping through each small change individually as if they were separate operations. Whi ...

What steps can be taken to ensure that the popover div remains visible when clicking inside it in a "dismissible popover" using Twitter Bootstrap with the data-trigger attribute set to "

I am struggling with a dismissible popover that contains a text box. When I click inside the text box to type, it disappears due to the "data-trigger="focus". Is there a way for the div not to disappear when clicked inside intelligently? Here is the releva ...

utilizing JavaScript to incorporate additional variables into a PHP form

I'm working on a project where I have a form that pulls data from a SQL database using PHP. I need to calculate the total value of only the checked boxes with JavaScript. Here's a snippet of my PHP code. Can someone help me figure out what I need ...

ReactJS did not get the expected function type for the onClick event listener, instead receiving an object type

I am encountering an issue where I expected the onClick event listener to be a function but instead got an object type error. Can someone offer guidance on how to resolve this problem? Below is a snippet of my code: render_detail_options = () => { ...

Is there a way to simultaneously modify several data variables within a Chart.js label?

I'm currently working on dynamically updating a line chart with two data entry points using the variable name "data." Take a look at the code snippet below: var lion = new Chart(ctx2, { type: "line", data: { labels: ["Apr", "May", ...

Moving the panel to follow the mouse cursor in Firefox Add-on SDK

Is there a way to show a panel on the screen at the exact position of the mouse? I'm finding it difficult to understand how to change the position of the panel in Firefox SDK, as the documentation lacks detailed information. ...

Looking for a horizontal scrolling menu in React?

I am currently working on a nextjs project and have decided to use Javascript instead of TypeScript. I need to implement horizontal scrolling functionality with both mouse wheel and touch support. After searching for react packages, I came across one calle ...

The inability to load the main.js script in index.html results in a blank website that only gets resolved upon refresh

Using the Vite / Rollup bundler with a Vue app as an example, we can see how this issue applies to any modern web stack. Vite automatically adds a hash to each js chunk, asset, and main.js file to indicate when changes have been made. However, there is an ...

Conditional statement based on the selection of an AJAX checkbox

I have multiple variables retrieved from form IDs that are then sent in a query string to PHP. One of the inputs is a checkbox, and I am attempting to use AJAX to set the variable's value based on whether it is checked or not. For example: if (do ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

Retrieve a specific string from the initial elements of the array

You're given an array: arr = ['Get your face right in there.', 'You&#8217;re like, wait, though, isn&#8217;t that too close? PUH-LEEZ. You and I both know that a person can never be too close to those browned lasagna edges that ...

Spice Up Your Spinner with New Items

I encountered an issue while trying to populate a spinner with items, resulting in the error message "Unfortunately my app has stopped working". To provide some context, I have defined a string array within strings.xml containing various items. Upon select ...