Is there a universal method for sorting arrays of arrays that sorts by each element starting from the first and continuing to the nth element?

Suppose I need to sort arrays of an array in ascending order, where the first element is min, then the second element is min, and so on. Here's how you can achieve this using the sort method:

Array with 2 elements

const arrayOfArray=[[2,1],[0,2],[1,3],[0,4]];
arrayOfArray.sort(function(a,b){
  if(a[0]!=b[0]){
    return a[0]-b[0];
  }
  return a[1]-b[1];
});
console.log(arrayOfArray);

Array with 3 elements:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];
for(let i=0;i<arrayOfArray[0].length;i++){
    arrayOfArray.sort(function(a,b){
      if(a[0]!=b[0]){
        return a[0]-b[0];
      }
      if(a[1]!=b[1]){
        return a[1]-b[1];
      }
      return a[2]-b[2];
    });
}
console.log(arrayOfArray);
    

When dealing with arrays containing more than 3 elements, the solution presented above becomes cumbersome with multiple if statements:

arrayOfArray.sort(function(a,b){
  if(a[0]!=b[0]){
    return a[0]-b[0];
  }
  if(a[1]!=b[1]){
    return a[1]-b[1];
  }
  .
  .
  .
  if(a[n-1]!=b[n-1]){
    return a[n-1]-b[n-1];
  }
  return a[n]-b[n];
});

But what if the length of the array is unknown or needs to be loaded dynamically? Is there a generic approach that avoids repetitive if conditions? Perhaps recursion or loops can help:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];
for(let i=0;i<arrayOfArray[0].length;i++){
    arrayOfArray.sort(function(a,b){
      return a[i]-b[i];
    });
}
console.log(arrayOfArray);

However, running the code gives unexpected results:

[
  [
    0,
    1,
    1
  ],
  [
    0,
    2,
    3
  ],
  [
    2,
    1,
    5
  ],
  [
    0,
    2,
    5
  ]
]

which does not match the desired outcome.

Answer №1

To achieve the desired outcome for arrays of any length, you can compare all elements in the input arrays by iterating through them in the sort function. Return the difference between elements if they are not equal, or return 0 if all elements in both arrays are equal:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];

arrayOfArray.sort(function (a,b) {
  for (let i = 0; i < a.length; i++){
    if (a[i] != b[i]) {
        return a[i] - b[i];
    }
  }
  return 0;
});

console.log(arrayOfArray);

Answer №2

While it might not work for every scenario, in this instance you can utilize string comparison:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];

const result = arrayOfArray.sort((a, b) => a.join('').localeCompare(b.join('')));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

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

Accessing the value of a stdClass object without utilizing a foreach loop

First of all, thank you to everyone who is taking the time to read this post. Here's my question: How can I extract the category_id values from these two stdClass objects within the categories array and add them to another array like $categories = ar ...

Middleware in Expressjs ensures that variables are constantly updated

I'm attempting to accomplish a straightforward task that should be clear in the code below: module.exports = function(req, res, next) { var dop = require('../../config/config').DefaultOptions; console.log(require('../../config/ ...

Get rid of the title on Superfish Menu in Drupal 7

Exploring Drupal for the first time, I've been able to find solutions to all my queries except one - removing the "Main Menu" header from my superfish menu. The region called superfish has successfully had superfish added to it, but I'm unable t ...

Attempting to allocate an array dynamically within a specific element of a vector containing structures

Currently, I am facing an issue where I have a vector of a point type (point being a structure with 2 integers and a pointer to another integer) and I'm attempting to dynamically allocate memory for the additional integer array within each vector elem ...

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

Refresh the copyright year by syncing with a time server

Not long ago, I found myself needing to update the copyright year on a website. Instead of using JavaScript to get the year from the system time, I began wondering if there was a way to utilize an internet time server for this purpose. I believe that util ...

Is JavaScript asynchronous when it comes to manipulating the DOM?

While conducting Javascript tests on the Android browser, I monitored the number of instruction counts executed on the CPU. The test code for JS is straightforward and embedded within HTML files located in the local directory of an Android device, not on a ...

The Div element seems to have a mind of its own, refusing

Check out my code on this link: http://jsfiddle.net/Pd7nm/ I'm trying to make the sidebar stop scrolling with the page once it reaches a certain point, but it just won't cooperate. I've attempted various solutions, but none seem to be effec ...

Endless scrolling results in a full loading rather than a step-by-step one

I'm currently working on implementing infinite scrolling on my website by following a tutorial I came across. However, instead of displaying only a few items at a time and allowing for continuous scrolling, the page loads up with all items at once. I& ...

Automatic cancellation of AJAX request

Having a strange issue that I need help with. I am using a standard ajax call to upload avatars from the user's PC to the server. However, sometimes I notice in Firebug that the request is being "Aborted" and marked in red after loading for some time ...

If the span id includes PHP data that contains a certain phrase

Hey there, it's my first time posting and I'm in a bit of a bind with this script... Let me give you some background information first I am trying to create a click function for a register button that will check the span id (e.g. $("#username_r ...

What are the ways to alter byte sequences?

Suppose I have an ELF file in Python with the following content: >>> data=open('file','rb').read() >>> data b'\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00& ...

The authentication strategy "github" is unrecognized

I am encountering an issue with online authentication on GitHub. Even after registering the new app on GitHub, the application continues to fail to redirect to OAuth. I have written the following code and am receiving an error message stating: Error: Unkn ...

Why are new lines being added to my package.json file, and what is their purpose?

I am the maintainer of an npm package and I've noticed that there are entries being added to package.json with underscore characters. These entries include information like the package's raw URL, specifications, and locations. "_args": [ [ ...

Choose elements in jQuery that lack a specific class

How can I efficiently select all elements with the .hi class that do not include the .image class? <div class="hi"> <div class="hue"> <div class="image"> 456 </div> </div> </d ...

Learn how to alter the string hues within a JavaScript Array to showcase them on a web browser

I was looking to update the string colors to white for a white display in the browser, but I'm unsure of how to proceed. After searching extensively online, I discovered that font color is no longer part of JavaScript so I'm exploring alternative ...

Using jquery.ajax to post to a single page without passing any variables

In order to capture the onclick event for a specific #id, I am retrieving form data and checking if $_POST['submit'] is set. If it is, I proceed to send an email. Although there are no errors, it appears that no data is being sent via post. < ...

Steps for including a 'close' button in Lightbox on Bootstrap 4

Apologies for my English... I found this code here, but it was missing the close button. Above on the Website I have, <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://cdnjs.clou ...

Guide on making a semi-transparent overlay with JavaScript in ReactJS

In my ReactJS project, I am working on an API request. After making the request, I want to display a transparent overlay on the current webpage along with Material UI's circular progress indicator (view it here: http://www.material-ui.com/#/components ...

Using the directive in AngularJS and passing ng-model as an argument

Currently, I am creating a custom directive using AngularJs, and my goal is to pass the ng-model as an argument. <div class="col-md-7"><time-picker></time-picker></div> The directive code looks like this: app.directive(' ...