Sorting a multidimensional array in JavaScript by a single column

I have successfully created a 4-dimensional array in JavaScript. One of the columns consists of String values, while the other three columns contain float values. I populated the first three columns using data from a JSON response, and for the fourth column, I calculated the magnitude based on the values in columns 2 and 3. Now, my task is to sort the entire array based on the values in column 4. Below is the code snippet that demonstrates how I initialized and filled the array. Could someone kindly guide me on how to implement sorting based on column 4?

     var labels = responseJSON.labels;
     var knowledge = responseJSON.knowledge;
     var interest = responseJSON.interest;

     var label_know_int_array = new Array(4);
     //array item 0 holds all the labels
     label_know_int_array[0] = new Array(200);
     //array item 1 stores knowledge values
     label_know_int_array[1] = new Array(200);
     //array item 2 saves interest values
     label_know_int_array[2] = new Array(200);
    //array item 3 calculates the magnitude of knowledge and interest
     label_know_int_array[3] = new Array(200);

     for(var i=0;i<labels.length;i++)
         {
                label_know_int_array[0][i] = labels[i];
                var knowVal = knowledge[i];
                var intVal = interest[i];
                label_know_int_array[1][i] = knowVal;
                label_know_int_array[2][i] = intVal ;

                var squareSum = (knowVal*knowVal) + (intVal*intVal);
                var distance = Math.sqrt(squareSum);
                label_know_int_array[3][i] = distance ;


         }

Answer №1

To achieve custom sorting, the Array.sort() method can be utilized

The Array.sort method allows for a callback function to be used for personalized sorting

Below is an example code snippet demonstrating this:

var arr = [
  {
    id : 8,
    name : "Alice"
  },
  {
    id : 3,
    name : "Bob"
  },
  {
    id : 1,
    name : "Charlie"
  }
];

// customized sorting
arr.sort(function (a, b) {
    if (a.id > b.id) {
       return 1;   //return positive values
    } else if (a.id < b.id) {
       return -1;  // return negative values
    } else {
       return 0;  // return zero for equal values
    }
});

By utilizing this callback function, you can tailor your sorting process based on specific requirements

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

Parsing JSON strings that contain apostrophes (single quotes)

Can you assist me in decoding the given string? var a = JSON.parse('[' + '{"NoteName":"it's my life","UserId":"100","NoteActive":true,"UserEmail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e6e3eaeee9 ...

Bring in various React components from separate files

I am struggling with using a component from another JS file in ReactJS. The error message "Header is not defined" keeps popping up. Just to clarify, I am working with ReactJS but without NodeJS involved. Here's the snippet of code causing the issue: ...

Encountering a parsing issue: an unexpected token was found, expecting "," instead

I'm encountering a Parsing error that states: Unexpected token, expected ",". I've been unable to pinpoint where the missing "," is located. Please refer to the image below for the exact line of the error. const cartSlice = createSlice({ name ...

Facing challenges in implementing a logic to showcase an intricate page on express.js (node.js) platform

Having trouble setting up a functional logic to display a detailed page showcasing the post title, image, and details. Currently, I've successfully created a list page that displays all the posts by the logged-in user with the title, image, and detail ...

Issues with jQuery custom accordion functionality in Internet Explorer, Safari, and Chrome browsers

When a corresponding <a> is clicked, my script should expand/collapse UL elements. It works perfectly in Firefox and you can check it out here. First, I load the jQuery library and then my own examples.js file which includes: function initExamples( ...

Cannot choose an option using JQuery Select2

Encountering an issue with Select2. The functionality seems to be working fine, except for the inability to select any option. Utilizing select2 version 3.5.3 along with KnockoutJS, CoffeeScript, and JQuery. Here is my select2 code: generateSelect3 =-> ...

Mastering WordPress Advanced Custom Fields - Leveraging Select Field Within an Array to Enhance and Customize Array Elements

I am currently building a WordPress website and utilizing the ACF Pro plugin. My goal is to have a select field with two values assigned to each option. The first value will serve as a heading, while the second will be a percentage figure (currently just a ...

Animation using jQuery is functional on most browsers, however, it seems to

After creating an animation to simulate an opening door using jQuery, I discovered that it works perfectly on Firefox 24, Chrome 28, and IE 8. However, Safari presents a problem - the door opens but then the "closed" door reappears at the end of the animat ...

PHP encountered a syntax error while attempting to access an array from the return value of a function

I encountered an issue with my code that is preventing duplicate data from being displayed. It works fine on my local machine, but I am getting the following error on the host: Syntax error, unexpected '[' in /home/eplus/public_html/vqmod/vq ...

Finding the average JSON value using d3.js

Here is the structure of a JSON file I am working with: [ {"id":1,"sex":"Female","programming":5, "project":7}, {"id":2,"sex":"Male","programming":8, "project":4}, {"id":3,"sex":"Female","programming":5, "project":6}, {"id":4,"sex":"Male","programm ...

You can submit a photo to a form as an attached file

I had a code that looked like this My goal is to simplify the process for users by allowing them to fill out additional information in a form without having to upload an image separately. I want to display the canvas image from the previous page in the fo ...

jQuery event.preventDefault not functioning as expected

I am attempting to use jQuery's preventDefault() method, but when I submit the form, it still displays the default behavior and reloads the page. Here is the code from index.html: <body> <script src="/socket.io/socket.io.js"></script& ...

What is the best way to avoid duplicating items in a $SESSION list?

I'm currently developing a basic shopping cart system using only session variables without the need for a database. This system will eventually be expanded to include databases and user logins. When a product is selected, I utilize the URL to add it ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

Retrieve information from a group of strings

I am working with a string collection that looks like this: SetDEL_Stores.Add(DealerCode + "," + ItemIdentityCode.Text + "," + decimal.Parse(Qty.Text) + "," + DateTime.ParseExact(ExpireDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture) + "," + BatchNu ...

The functionality of the Javascript window.print() method is limited to a single use

I've been working on an Angular project and I have the following code snippet implemented in one of the components. Everything works fine when I try to print for the first time using the onClickPrint() method, but it doesn't seem to trigger when ...

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

The feature to "Highlight text on the page" in React-pdf is currently malfunctioning

I am currently working on incorporating the pdf highlighting feature from React-pdf: import React, { useMemo, useState } from 'react'; // import { Document, Page } from 'react-pdf'; import { Document, Page } from 'react-pdf/dist ...

the ability to utilize the @click glyphicon signal

In this scenario, as soon as I type something into the input field, the glyphicon-remove icon will appear. Upon clicking on it, the intention is for it to reset the search input. Below is the code snippet: <div class="form-group has-feedback has-feedb ...

The checkbox within the modal popup is failing to trigger the mousedown event on the external popup button

In the world of Drupal, there exists a unique phenomenon known as the modal popup - essentially a dialog box that appears within an iframe. One user found themselves faced with the challenge of triggering a mousedown event on a submit button located outsid ...