What is the best way to compare two 2D arrays in JavaScript?

Having an issue comparing two 2D arrays in javascript, looking to output "true" if the arrays are the same.

This is the code I experimented with:

`

function check(){
   
    if (data.every() === solution.every()){
        alert("example");
    } else {
        console.log("Data Array: " + data);
        console.log("Solution Array: " + solution);
    }
  
}

`

It seems my solution only functions with two 1D arrays. Seeking help and guidance from someone knowledgeable in this area.

Note: Utilizing jquery and native js only.

Thank you in advance.

~Luca

Answer №1

Here's how I would approach this problem:

function compareArrays(array1, array2)
{
 if(array1.length !== array2.length) return false;

for(let i=0;i<array1.length;i++)
{
 if(array1[i].length !== array2[i].length) return false;
 for(let j=0;j<array1[i].length;j++)
 {
  if(array1[i][j] !== array2[i][j]) return false;
 }
}
return true;
}

If you're looking for a solution that can handle arrays of any dimensions, a recursive version would be more suitable. However, for 2-dimensional arrays, the above code should suffice.

Answer №2

This script is designed to function with any number of dimensions:

const createRandomArray = (n,m) => Array(n).fill(0)
  .map(_=>Array(m).fill(0).map(_=>10*Math.random()|0))

const checkEquality = (a,b) => Array.isArray(a) ?
  a.length===b.length && a.every((e,i)=>checkEquality(e,b[i])) : a===b

const a = createRandomArray(3,3)
const b = createRandomArray(3,3)
const c = createRandomArray(3,5)
const d = createRandomArray(6,7)
const e = cloneArray(a)

console.log(checkEquality(a,b))
console.log(checkEquality(a,c))
console.log(checkEquality(a,d))
console.log(checkEquality(a,e))

Answer №3

To meet this requirement, you can easily accomplish it by following the steps outlined below:

  • Flatten both of the 2D arrays into a single 1D array.
  • Verify the length of each array and compare each item using the Array.every() method.

Take a look at the Live Demo:

const data = [[1,2,3], [4,5]];
const solution = [[1,2,3], [4,5]];

const result = (data.flat().length === solution.flat().length) && data.flat().every((item, index) => item === solution.flat()[index]);

console.log(result ? 'Both arrays are equal' : 'not equal');

Answer №4

One suggestion that many individuals propose is to utilize the JSON.stringify() method. This enables us to serialize each array and then compare the two serialized strings. An uncomplicated implementation of this concept would resemble the following:

function verify(){
   
    if ( JSON.stringify(data) === JSON.stringify(result) ){
        alert("message");
    } else {
        console.log("Data Array: " + data);
        console.log("Result Array: " + result);
    }
}

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

Incorporating an image as a clickable element instead of a traditional button using HTML and

Here's the issue at hand: I currently have "+" and "-" icons at the end of each row to add and delete rows as needed. However, I would like to replace the "-" icon with a trashcan symbol instead. I attempted to do this by replacing it with an image s ...

Label it as submit ID rather than value or label

Check out this awesome plugin called https://github.com/aehlke/tag-it. It's really cool! Here is the issue I'm facing: <input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true"> Tags:<br ...

Convert the array into an HTML table, displaying empty cells where there are missing values

I have a collection of numerical values arranged in ascending order from 1 to 80, with each value being unique. $numbers = array( "1", "3", "5", "6", "12", "13", "15", "20", "24", "28", "32", "33", "34", "42", "47", "49 ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

Is there a way to include this function in an array without triggering it right away?

In my coding project, I am working with an array of functions that return jQuery deferred AJAX objects known as phoneAjaxCalls. The main function called newPhone is where multiple calls are being pushed and it requires two arguments. function newPhone(tlc ...

Adjust the height of the container div for the carousel according to the length of the text displayed

My image carousel features description content positioned on the right for wide-screen windows. However, I want the description to shift below the images when the browser window reaches a certain breakpoint. The challenge I am facing is that the height of ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

What determines why the input value is restricted to being of type string?

In my ReactJS component, I am struggling to set the state value as an integer using setState. This is causing issues with the radio button not being checked. constructor(props) { super(props); this.state = { frequency: 1, } handleSelectChange(eve ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

Obtain the outline shape in ThreeJS (duplicate border)

When working with a geometry, I often need to view it from different angles. For example, if I position my camera from the top, I want to be able to extract the outline of the geometry as a new shape. This allows me to then Extrude this shape further. In R ...

Managing the expiration time of a Cookie with ngx-cookie-service: Explained

Currently, I am utilizing ngx-cookie-service in my Angular application. According to the official documentation, it is mentioned that a third parameter can be added for defining the expiration time as shown below: this.cookieService.set('CookieName&ap ...

Ensuring that the desired DOM elements have loaded before attempting to manipulate them in Vue.js

I've been struggling with this issue for the past day and I'm completely stuck. In my vue file, there's a method that operates like this: methods: { showSlides(n) { let slides = document.getElementsByClassName("mySlides"); ...

Enhance the flight experience of a helicopter with jQuery game by adding smoother controls

I'm currently experimenting with creating a basic game. In this game, the user controls a helicopter and can fly it up and down. Although I have successfully implemented the basic functionality where holding the screen makes the helicopter ascend an ...

Having trouble with the line of code right before a $timeout in AngularJS

I am wondering about an issue in my code. vm.showSuccess = true; $timeout(function() { close(); }, 2000); vm.showSuccess = false; Interestingly, the timeout function is executing properly but the first line seems to be ignored. This piece of code is me ...

Guide on displaying a real-time "Last Refreshed" message on a webpage that automatically updates to show the time passed since the last API request

Hey all, I recently started my journey into web development and I'm working on a feature to display "Last Refreshed ago" on the webpage. I came across this website which inspired me. What I aim to achieve is to show text like "Last Refreshed 1 sec ago ...

Concealing divs without values in ASP.NET MVC

I am working on an AJAX call to fetch data from the back-end and populate divs with it. Below is my code for the AJAX call: $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action(" ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Change events are not being received upon clicking the radio buttons

Hey friends, I'm trying to set up backbone events for when radio buttons are clicked. Here are the radio buttons I have: <p><label for="pays">Pays now</label><input id="pays" name="pays" type="radio" value="1" class="_100"/>&l ...

The most recent version of Autonumeric now permits the inclusion of a decimal point, even if the decimalPlaces parameter

I need to ensure that only whole numbers are allowed in the input textboxes, while also displaying a currency symbol and commas. I am using the most recent version of Autonumeric JS for this purpose. Even after setting the decimalPlaces property to 0, I a ...