Arrange an array of two dimensions based on characters and digits

I am looking to arrange a two-dimensional array containing both numbers and letters using JScript, not Javascript. Even though JScript is the native Microsoft JS engine used in Windows Scripting and Internet Explorer, I will still refer to it as JavaScript for simplicity's sake. Here is the array I want to sort:

var arr = [
  ['D1-45-32', 'Sneaker'],
  ['11-12-54', 'Ball'],
  ['34-56-12', 'House'],
  ['Y5-78-89', 'Coke'],
  ['11-11-11', 'Ball_1']
];

The desired order after sorting should be:

[
  ['11-11-11', 'Ball_1'],
  ['11-12-54', 'Ball'],
  ['34-56-12', 'House'],
  ['D1-45-32', 'Sneaker'],
  ['Y5-78-89', 'Coke']
]

My attempted solution involved using the following code block:

arr.sort(function(a,b){
  return /[A-Za-z]/.test(a) - /[A-Za-z]/.test(b) || a.charCodeAt(0) - b.charCodeAt(0)
});
console.log(arr);

Is there a simpler way to achieve this sorting using a loop? Any suggestions would be appreciated. Thank you!

Answer №1

Hello! I made some adjustments to the code for you:

let items = [['D1-45-32','Sneaker'],['11-12-54','Ball'],['34-56-12','House'],['Y5-78-89','Coke'],['11-11-11','Ball_1']];

items.sort((x, y) => {
  if (x < y) {
    return -1;
  }
  if (x > y) {
    return 1;
  }
})
console.log(items);

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

Enhance Your Vue Tables with Unique Custom Filters

I'm currently working on implementing https://github.com/matfish2/vue-tables-2 in Vue 2.1.8. Everything seems to be functioning flawlessly, but I need to incorporate custom filters to format certain fields based on their values. In my options object ...

Removing elements from a multidimensional array in PHP using unset function

I am working with a multidimensional array and I need to figure out how to remove a specific element from it. I have tried using unset() and array_pop(), but unfortunately, neither of them has worked for me. For example, when attempting to use unset(): e ...

Can one retrieve an express session using the sessionID given?

I have a NodeJS Express application with express-session that works well, however, it needs to be compatible with a cookie-less PhoneGap app. My question is: Can I access the data in an express session using the sessionID? I was thinking of adding the se ...

How can I dynamically append content to the DOM when a user clicks?

On my form, I have an input field that allows users to click an add button and a new input field will appear below it, with the option to repeat this process indefinitely. However, I am facing an issue with adding an input field to the DOM upon a click eve ...

Transmitting an Associative Array from one PHP script to another using AJAX communication in PHP

After receiving an associative array from PHP via $_GET through the following URL: example.com/example.php?itemcount[A]=2&itemcount[B]=3 The result of using json_encode() turns out to be: { "A" : "2", "B" : "3" } I am now looking to send this data to ...

There seems to be a JSON syntax error on the website for tracking Covid-

Hi everyone, I'm currently working on a Covid-19 tracker website and facing an issue that says: 'SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data' ; Being new to web development, I am unsure about what&apo ...

Code in JavaScript: Generating Random Number within a Loop

Can anyone help me come up with a unique JavaScript loop that can guess a correct number within the range of 1-500? I want each iteration of the loop to generate a new number that has not been guessed before, but it should guess in a random order. For ex ...

I'm puzzled as to why I keep receiving unexpected months despite utilizing the BETWEEN method in my query

It just dawned on me that I mistakenly posted the wrong code for my question earlier Despite setting the BETWEEN method in my statement, I am still getting random months when trying to run it in my nodejs with mysql2. Why is that happening? SELECT u.d ...

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

Implementing a jQuery event listener for an event that requires another event as a parameter

My goal is to trigger the function scheduleAdd when the enter button is pressed, but only if an input with the id 'addSchedule' is currently in focus. This is what I have so far: $('#addSchedule').focus(function(e) { var evt = ...

The aoColumns feature in datatables is experiencing a malfunction

Trying to manage the value of aoColumns from another PHP page has been a bit challenging for me. When I use a static value, it works fine, but when trying to retrieve it dynamically, I encounter some issues. $aoColumn = array("null","null","null","{bSorta ...

To determine if an AJAX request is synchronous or asynchronous using Browser Developer Tools

Is there a method to verify if a specific ajax request is asynchronous or synchronous using Browser Dev Tools such as Chrome Developer Tools or Firebug? The HTTP Request Header for an ajax request does not specify whether it is sync or async. X-Request ...

Simple steps to update array key values in PHP

I am attempting to retrieve word counts from HTML documents stored in a specific folder. <?php $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('fulltext/course')); $fulltext_course_files = array(); foreach ($rii as $f) { ...

There was an unexpected error: Unable to access the 'bool' property of an undefined object

{ "name": "unique-react", "version": "2.0.1", "private": true, "scripts": { "start": "webpack-dev-server --hot --port 3002 --open --inline", "build": "cross-env NODE_ENV=production rimraf dist && webpack", "package": "webpack -p ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

Tips for determining if a user is refreshing the page or navigating to a different page

Scenario: I need to store a specific variable in the local storage every time a user exits the page. By utilizing the window.onbeforeunload method, I am able to capture the event when a user is leaving the page. However, I want to assign different values ...

Should classes/interfaces/functions be consistently prefixed with the App acronym as a best practice?

As I delve into my Angular project, I find myself contemplating the idea of using the App acronym as a prefix for all Classes, Interfaces, and Functions. This practice is commonly seen in tag components, where adding the App acronym helps avoid conflicts i ...

JavaScript: Struggles with utilizing a function as an argument and later executing it inside a nested function

I've been struggling with defining a new function, and I need help resolving it. Here's an example that I was initially referencing: Pass arguments into ajax onreadystatechange callback? I wasn't able to find the solution through research, ...

Is there a way to deactivate the parent background div when a child container div is in use?

Is there a way to deactivate the main background container that holds a grid with data? Within this grid, users have options for sorting and exporting the data into formats like csv/pdf. Additionally, there is a filter button on the grid that, when clicked ...

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...