Sorting options tailored for arrays within arrays

Here is an array with nested arrays:

var array = [
  ['201', 'Tom', 'EES', 'California'],
  ['189', 'Charlie', 'EE', 'New Jersey'],
  ['245', 'Lisa', 'EEF', 'New Jersey'],
  ['743', 'Niall', 'EEC', 'Chicago'],
  ['653', 'Tim', 'EES', 'Miami'],
  ['333', 'Dev', 'EE', 'Washington'],
  ['333', 'Rhonda', 'EEC', 'Washington']
]

I would like the array to be sorted based on the third value in the subarrays, following the order [EE, EES, EEC, EEF].

The sorted array should look like this:

[
  ['189', 'Charlie', 'EE', 'New Jersey'],
  ['333', 'Dev', 'EE', 'Washington'],
  ['201', 'Tom', 'EES', 'California'],
  ['653', 'Tim', 'EES', 'Miami'],
  ['743', 'Niall', 'EEC', 'Chicago'],
  ['333', 'Rhonda', 'EEC', 'Washington'],
  ['245', 'Lisa', 'EEF', 'New Jersey']
]

Please note that the original array may vary in length, but the order of the elements should remain as specified.

Thank you for your help!

Answer №1

// Check out this code snippet! Utilize array.sort(...) to achieve this


var array=[['201','Tom','EES','California'],['189','Charlie','EE','New Jersey'],
['245','Lisa','EEF','New Jersey'],['743','Niall','EEC','Chicago'],['653','Tim','EES','Miami'],
['333','Dev','EE','Washington'],['333','Rhonda','EEC','Washington']];


let _result = array.sort(
    function(a, b){
        if (a[2].toLowerCase() < b[2].toLowerCase()) return -1;
            if (a[2].toLowerCase() > b[2].toLowerCase()) return 1;
            return 0;
    }

)

console.log(_result);

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

How can I ensure the button remains disabled until all inputs are completed in Redux form?

I am currently studying a react-redux form example that you can find at the following link: In this example, the submit button is enabled if the user fills in at least one input field. I am curious to know if there is a way to enable the button only when ...

Angular - remove elements from an array within a directive when encountering a source error

If an image does not exist, I need to remove the item and push the next one inside ng-repeat. Currently, I am using a custom directive called "noImage". myApp.directive("noImage", function() { return { link: function(scope, element, attrs) { ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...

Looking for a new slider option to replace the traditional Conveyor belt slideshow?

I have successfully used the Conveyor belt slideshow script from http://www.dynamicdrive.com/dynamicindex14/leftrightslide.htm. Now, I am looking to find another script that works similar to this one. Does anyone have any recommendations for a tool that ...

Utilizing the dojo.xhrget() Method to Showcase Information in the Dojogrid

Trying to showcase a dataset retrieved asynchronously from the server using the dojo.xhrget() method. The intention is to update the grid with new values each time a user interacts with the content pane, without refreshing the entire page. However, running ...

Error occurs when JSON.parse is used

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var data = "{ 'name': 'John' }"; var result = JSON.parse(data); </script> ...

Changing the size of a struct array in a function

Exploring ways to dynamically insert new elements into an array of structs has been a challenge. Below is a basic example that crashes unexpectedly. It seems that passing a pointer struct data **arr to the function is necessary for reallocating memory and ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Help! My C program is printing out weird results - what mistake did I make?

#include<stdio.h> #include<string.h> int main() { int j; char password[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; j = strlen(password); printf("Size = %d&b ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Authentication - The success callback of $http is executed rather than the error callback

I seem to be facing an issue with authentication in a MEAN stack app, possibly due to my limited understanding of promises and the $http's .then() method. When I try to authenticate to my backend Node server with incorrect credentials, the success cal ...

When a value is assigned to a numpy array element, it remains unchanged

I'm absolutely stumped by this problem. I've been attempting to modify the elements of a numpy array without success: import numpy as np c = np.empty((1), dtype='i4, S, S, S, S, S, S, S, S, S') print(c) c[0][1]="hello" c[0][2]='he ...

Tips for validating Enum Strings using the newest version of Joi?

Is there a way to validate Enum String? In the past, I followed this advice from: https://github.com/hapijs/joi/issues/1449 enum UserRole { Admin = 'admin', Staff = 'staff' } const validator = { create: Joi.object().keys({ ...

Vue component's data remains stagnant within created() hook

I'm currently working on transforming the API response to make it more suitable for constructing two tables. Despite adding debugging outputs within my function in created(), I am witnessing the desired output temporarily, but upon further examination ...

Is there a way to incorporate a deletion feature within a list of items using JavaScript?

When adding a new item, I want to include a delete button next to it so I can easily remove the item by clicking on the button. However, I am having trouble figuring out how to implement this functionality using JavaScript. You can view my code snippet he ...

What is the best way to execute multiple controller functions for a single route?

I have a specific route set up for users to submit loan applications. What I want to achieve is to call different controller functions based on the amount of the loan that the user is applying for. app.use('/submitLoanRequest50kMore', mw1, mw2, ...

Issue with Google Charts - Chart is unable to render because data table has not been defined

Using Ajax, I attempted to set an Interval for my Google Chart, but unfortunately, the Chart is not being drawn. Instead, I repeatedly receive the error message: "Data table is not defined." every 5 seconds. If you want to see a screenshot of the error mes ...

Combining two ranges into a 2-dimensional array in Ruby

I'm looking to combine two ranges into a 2D array in Ruby. After trying the zip method, I realized it didn't give me the desired output. (0..2) and (0..2) # should transform into => [[0,0],[0,1],[0,2], [1,0],[1,1],[1,2], [2,0],[2,1],[2,2]] ...

Using AngularJS ui-router ui-sref results in the error message "Uncaught TypeError: Cannot read property '0' of undefined."

I am currently working on an angularJS component that utilizes ui-router with 2 straightforward route states. export default function Routes($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('details', { ...

Having issues with AJAX and button submit while trying to upload a file using Flask

I've been attempting to incorporate a file upload feature (specifically a .csv file) using bootstrap, and then submit it by clicking on a button. I've experimented with various methods to implement the file upload functionality, but haven't ...