What is the fastest and most efficient method to confirm that all rows in a 2D array are of equal length?

Imagine you have a 2D array like this:

const matrixRegular = [
    ['a', 'b', 'c'],
    ['e', 'f', 'g'],
];

Now, let's think about how we can check if every row in this matrix has the same length. For example, the matrix above is valid, but the one below is not:

const matrixIrregular = [
    ['a', 'b', 'c'],
    ['e', 'f']
];

Is there a neat and elegant way to accomplish this? Here's a one-liner that does the trick:

const isRegularMatrix = matrix => new Set(data.map(row => row.length)).size === 1

Simply convert the matrix into an array containing just the row lengths, and then use a Set to check if all elements are duplicates (i.e., have the same length), resulting in a size of 1.

Answer №1

To achieve this, you can utilize the every() method in combination with comparing the length of each array to the length of the first array.

const isRegularMatrix = matrix => matrix.every(x => x.length === matrix[0].length)

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

How to store selected checkbox values in an array using AngularJS

Check out this code snippet: <tr ng-repeat="doc in providers"> <td><input type="checkbox" ng-true-value="{{doc.provider.Id}}" ng-false-value="" ng-model="ids"></td> </tr> {{ids}} I am trying to store the values of ...

Creating a Date Computation Tool that Adds Additional Days to a Given Date

I have a challenge where Date 0 represents the start date, Date 1 is the result date after adding a certain number of days (NDays). I am looking for help in JavaScript to calculate Date0 + NDays = Date1. Please assist me as my coding knowledge is quite l ...

Using percentages for sizing and margins in CSS

Looking to create a visually appealing page that always fills the entire screen? Check out this code snippet that does just that: #posts{ width:100%; height:auto; background:#666; } .entry{ float:left; margin-left: 4%; margin-top:10 ...

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

Stopping a requestAnimationFrame recursion/loop: Tips and Tricks

I am developing a game using Three.js with the WebGL renderer that goes into fullscreen mode when a play link is clicked. To handle animations, I utilize the requestAnimationFrame method. The initialization of the animation process looks like this: self. ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Is there a way to retrieve all active HTTP connections on my Express.js server?

In my express server app, I am implementing SSE (server send events) to inform clients about certain events. Below is the code snippet from my server: sseRouter.get("/stream", (req, res) => { sse.init(req, res); }); let streamCount = 0; class SS ...

Getting undefined while trying to iterate through data on a next js page using getStaticProps. What could be causing this issue?

Encountering difficulties while trying to output the page meta data in next.js when I execute: npm run build An error is thrown with the following message: Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/pre ...

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...

Error in AJAX POST: base64 string formatting issue

Struggling with making an AJAX POST successfully upload and retrieve a base64 string to/from my SQL database. Upon receiving the string from the database via AJAX, it appears to be the same base64 string, but with random line breaks that render it non-func ...

Save and showcase SQL, PHP, HTML, and JS code exactly as it is preserved in MYSQL database

Is there a way to store and display complete JS, PHP, and HTML code in MySQL without altering the format? The stored PHP code should appear as: <?php echo "something"; ?> And not just: something For JavaScript: <script> document.write(&ap ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

Display the datepicker beneath the input field

I successfully integrated the datepicker, but I prefer for the calendar to display below the date input field rather than above it. HTML5 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv=" ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

Ensuring that two operators are not consecutively placed in a Javascript calculator-validation guide

After creating a basic calculator using HTML, CSS, and JavaScript, I encountered an issue. When validating user input, the calculator currently accepts multiple operators in a row. To address this, I attempted to prevent consecutive operators by checking ...

In need of a method to create PDFs using client-side technology (specifically AngularJS)?

I need a method to create PDFs using AngularJs that includes HTML, CSS, and JavaScript elements. I have tried two options: jsPDF (which does not support CSS) Shrimp (built on Ruby) Neither of these solutions fit my needs. Is there another way to accom ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

Change the label's class when the input area is selected

Looking to add a new class to a label when its corresponding input element is in focus. A form consists of 10 input fields and 10 labels, one for each field. const inputFields = document.querySelectorAll('.form-control'); console.log(inputFie ...

Attempt to refresh the JSON data on a website by incorporating an image link from Last FM

I'm relatively new to React Native and have been struggling for quite some time with a persistent issue. I am parsing an online JSON file that contains artist and track information. The only missing piece is the image URL, which I am trying to fetch ...