Sorting a 2D array in Javascript based on numerical values

I've come across a few similar posts regarding this issue, but none have provided solutions that work for my specific situation. I'm feeling lost on how to solve this problem (like Sort a 2D array by the second value)

Let me explain the challenge I'm facing in JavaScript;

I have two arrays that I'm using to generate a chart in a third-party tool. Here are the variables I'm working with;

label["Stock A", "Stock B", "Stock C", "Stock D"]

value["200", "1000", "900", "800"]

I would like to organize this data into a 2D array

sorted["Stock B, 1000","Stock C, 900", "Stock D, 800", "Stock A, 200"]

I want to sort based on the numerical value, if possible. The issue arises when I try the solution from the aforementioned question, as it only compares one value with another. I need it to go through all values stored in the array.

Last week, I stumbled upon a complicated method that sorted values like 100 and 1000 next to each other - which I initially thought was due to them not being integers, but that wasn't the case. In frustration, I deleted that code last Friday.

I'm hoping that someone out there can offer guidance to a novice coder like me. Since the values come in as strings, they'll need to be converted to integers.

The array could potentially have an unlimited number of entries, and once they're correctly sorted, I need to keep the top 10 and group the rest together with a total count - resulting in 11 entries. But sorting is the first hurdle I must overcome.

Thank you in advance for any assistance.

Answer №1

I am interested in converting this into a 2D array

sorted["Stock B, 1000","Stock C, 900", "Stock D, 800", "Stock A, 200"]

It's important to note that what you have is actually a single dimensional array of strings. To create a true 2D array, it should look like this:

sorted = [["Stock B", 1000], ["Stock C", 900], ["Stock D", 800], ["Stock A", 200]];

To sort this 2D array by the second value, you can use the following code snippet:

sorted.sort(function(a, b) {
    var avalue = a[1],
        bvalue = b[1];
    if (avalue < bvalue) {
        return -1;
    }
    if (avalue > bvalue) {
        return 1;
    }
    return 0;
});

Alternatively, you could consider using a single-dimensional array of objects for better organization:

sorted = [
    {name: "Stock B", quantity: 1000},
    {name: "Stock C", quantity: 900},
    {name: "Stock D", quantity: 800},
    {name: "Stock A", quantity: 200}
];

This array of objects can be sorted as well with the following code:

sorted.sort(function(a, b) {
    var avalue = a.quantity,
        bvalue = b.quantity;
    if (avalue < bvalue) {
        return -1;
    }
    if (avalue > bvalue) {
        return 1;
    }
    return 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

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

Guide to executing a batch file using electron

I've been struggling all morning to find a solution. I've gone through several tutorials, but I still can't wrap my head around how this should work. In my Electron app, there is a button that, when clicked, should execute a batch file (hpm ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

Modify the height of an element in real-time using jQuery

I'm looking to dynamically adjust the height of a div based on another element, but only if that element does not have the class collapsed (which is used in a Bootstrap toggle collapse feature). The initial setup seems to work fine, however, when I i ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

How can I pass arguments from a Python command line program (compiled to an EXE) to a JavaScript file?

As I work on developing a node program, I've come across certain abilities that Python possesses which JavaScript lacks, such as utilizing Python-specific modules. To bridge this gap, I made the decision to compile Python files into EXE and then invok ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

The transition effect is not activated when using the MUI Drawer with react-router-dom

My goal was to merge the persistent drawer similar to the example on the MUI website with react-router-dom. However, I encountered a problem where the transition effect no longer seems to work properly. The paragraph does not resize to accommodate the open ...

What's the reason for the mousewheel functioning in Chrome but not in Firefox?

I am currently using CSS to enable scrolling up and down a popup page with just the mousewheel, but I'm facing an issue with it not working in FireFox. Surprisingly, it works fine in Chrome with the use of overflow-x:hidden; and overflow-y:auto; prope ...

Implementing change event to activate select dropdown with jQuery

Is there a way to modify the code so that select2 and select3 are disabled by default, but become enabled only when an option is selected in the previous select dropdown (excluding the placeholder "Select your option")? In addition, I want the first place ...

Expanding list - Using individual toggles to expand and collapse multiple list items

I stumbled upon an interesting jquery script that allows for a collapsible sub menu within a list. After implementing this code: $('.menu-item-has-children').prepend('<a id="fa-menu" href="#"><i class="fa fa-plus"></i>< ...

Designing a unique shape geometry using THREE JS

I've been struggling to replicate an existing city in a 3D environment using THREE.js. I have coordinates for approximately 1000 buildings, each with a varying number of corners making it impossible to use standard cubeGeometry. I attempted to create ...

Error encountered with Node.js clustering

Hey there! I'm currently diving into the world of node.js and javascript. My goal is to build a cluster.js using the nodejs cluster module, where at the end of my if statement I invoke server.js to kickstart the application. Here's my cluster.js ...

JavaScript encountering issues when parsing a string that was serialized using Gson in Java

This question is unique and differs from this one as it specifically addresses the representation of JSON strings serialized from Java in literal form in JavaScript, with a focus beyond just double quotes. In my scenario, I am serializing a JSON object in ...

Choosing an item in an AngularJS select directive from an external origin

I'm currently working on developing a form using Angular JS for editing venue details such as address and city. The backend system is powered by Django and offers a REST API (Django Rest Framework) which I am interfacing with through Restangular serv ...

Which regular expression should be used to validate names with international characters?

Currently in my PHP project using Codeigniter, I am implementing form validation. Specifically, I have configured the validation rules for the name field like this: $this->form_validation->set_rules('name', 'Nombre', 'requir ...

Using NextJs <Script> is only effective after a page has been reloaded

Currently delving into the world of NextJS and encountering an issue with integrating a third-party ebay script onto one of my route pages. The script only seems to appear sporadically upon reloading the page. However, when navigating to the store page via ...

Troublesome CSS Zoom causing issues with jQuery scrollTop

As I design a website that has a fixed width and zooms out on mobile browsers, I've opted to adjust the zoom using CSS rather than viewport meta tags: html, body { zoom: 0.8; } It's been effective so far, but now I'm facing an issue wi ...

What is the best way to transmit two variables in a single message with Socket.io?

My goal is to send both the clientid and username through the socket communication. client.userid = userid; client.username = username; client.emit('onconnected', { id: client.userid, name: client.username }); I attempted this approach, how ...

Navigating sub-domains swiftly

Having trouble setting up sub-domains and routing in Express Node. I need to direct users based on their device and browser type. If the user is on a desktop, they should be routed to web.. If they are on a mobile device, it should be mobile.. And if the ...