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

Carousel Alert: Ensure that every child within the list is assigned a distinct "key" property

I'm experiencing an issue that is proving to be more challenging than usual, as it appears to be related to a specific library. I understand that using a key from a file is not ideal, but the plan is for it to come from a database in the future. Libr ...

JSON syntax error: "r" is not a valid token at the beginning position

Currently, I am in the process of developing a web server that is based on STM32 MCU. The workflow involves the browser sending a request to the MCU, which responds with a web HTML file. Users can then adjust parameters and use a form to submit them back t ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Is there a messaging app that provides real-time updates for when messages are posted?

I am in the process of developing a messaging application. User1 sends out a message, and I want to display how long ago this message was posted to other users - for example, "Posted 9 min. ago", similar to what we see on sites like SO or Facebook. To ach ...

Issues with Mega Menu functionality preventing items from being clickable and links from properly navigating

Recently, I encountered a strange issue related to the integration of a mega menu found at . Unfortunately, despite integrating the mega menu, the Category and sub category links seem unresponsive - they are not directing me to the desired links. I suspec ...

Different browsers have varying ways of handling transition end callbacks with AddEventListener()

Each browser has its own transition end callback. Therefore, I find myself needing to use addEventListener() for each one. addEventListener('transitionend', function() { // code here }); addEventListener('webkitTransitionEnd', funct ...

Why Jquery's nth-child selection and conditional formatting are failing to work

I am working with a table and need to format specific data fields based on their content. For instance, any field less than 95% should be highlighted in red. Below is the jQuery code I am using: $(function(){ $('#ConditionalTable td:nth-child(2n ...

Having trouble retrieving POST parameters

I'm attempting to send a post parameter (key: test, value: somevlaue) using PostMan with the restify framework. I've tried two methods, but both are failing: The first method results in this error: { "code": "InternalError", "message": "Can ...

Exploring error management in Vue3 and Vite when deploying to production

After following the error handler setup in the Vue documentation, I encountered a difference between using it on the development server and in production. The error handler effectively pinpointed the component and line number where the error occurred durin ...

Is it possible to modify the HTML/CSS of a child component using the parent component in Angular 2+?

Is there a way to dynamically add text and style to a specific row in a child component based on the parent's logic? (parent): <body> <child-component></child-component> </body> (child): <div *ngfor = "let record in r ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

Angular 1.5 component causing Typescript compiler error due to missing semi-colon

I am encountering a semi-colon error in TypeScript while compiling the following Angular component. Everything looks correct to me, but the error only appears when I insert the this.$routeConfig array: export class AppComponent implements ng.IComponentOp ...

Getting callback data from a function in the AWS SDK without using asynchronous methods

I have a code snippet that fetches data from AWS using a function: main.js const { GetInstancesByName } = require("./functions"); var operationmode = "getinstances"; if (operationmode == "getinstances") { let getresult = ...

Discovering an item within an array of objects using the find method in Ajax

Within my backend PHP code, I iteratively define the following: foreach ( $data as $res ){ $approved[ ] = [ 'id' => $count, 'title' => "some title" ]; $count++;$title=... ) This eventually leads to the creation ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...

Encountering issues with fs.writeFile function in a freshly set up Vue project

After initializing a new Vue project with vue cli, I encountered an error when attempting to write files in the main.js file. Below is the code snippet that caused the issue: const fs = require('fs'); // Data to be written to the file. let dat ...

Sharing tips for sending error objects to a socket.io callback

Utilizing callbacks with socket.io Client side code : socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); Server side code : socket.on('someEvent', function(data, callback) { callback(ne ...

Every div must have at least one checkbox checked

Coding in HTML <div class="response"> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> <input type="checkbox" /> </div> <div class="response"> <input type="check ...

Refreshing a view in Laravel after a successful insertion using JQuery Ajax

I have been successfully inserting records into a table using jQuery ajax, and receiving a flash message confirming the successful insertion. However, I am now facing an issue where I do not know how to reload the table to reflect the changes after the rec ...

Presentation comparing ng-show and ng-hide efficiency

Introduction:- There may be some who opt to use ng-show instead of ng-hide="!true", while others choose ng-hide over ng-show="!true". Technically, the ng-hide directive is not necessary. However, Angular introduced it for a standard coding structure. Plea ...