Arrange the 2D array in JavaScript by utilizing both categories

Looking to organize a 2D array based on two specific criteria:

[ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ]
  1. Sort by number in ascending order

  2. Then arrange alphabetically in descending order

The desired output is the who word. Currently, the first step has been accomplished using the code below:

arraySorted = arrCom.sort((a, b) => a[1] - b[1] || a[0] - b[0]);

Answer №1

If the initial comparison yields a result of 0 (indicating identical numbers), utilize the localeCompare method to perform an alphabetical comparison:

const items = [ [ "apple,", 4 ], [ "banana,", 3 ], [ "orange,", 6 ], [ "cherry,", 5 ] ];
items.sort(
  (x, y) => x[1] - y[1] || y[0].localeCompare(x[0])
);
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

Filtering arrays using Vue.js

I have developed a sample e-commerce website to showcase various products to potential customers. The website boasts features like filters, search functionality, and sorting options to enhance the user experience. However, I've encountered an issue sp ...

What steps do I need to take in order to transform this code into a MUI component complete with

Having some trouble converting my hero banner code to MUI in a React project. The styling is not coming out correctly. Here is the HTML code: <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120 ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Determine if a dropdown menu includes a certain string within a designated group option

I have a specific condition in my code that states: "Add a new option if the select box does not already contain an identical option." Currently, a 'Hogwarts' option will only be added if there is no school with the same name already present. No ...

Leverage the power of Angular.JS and ng-table to effectively summarize values in your

I received the following JSON data: var scholars = [{"FirstName":"John","LastName":"Doe","Unit":"PA","Institution":"University of Haifa","teken":1,"FirstYearActive":"2007","hIndex":"3","j2014":0,"j2013":4,"j2012":3,"j2011":0,"j2010":0,"j20052009":2,"j2 ...

Converting a 3D image array in NumPy to a 2D array

I am working with a 3D-numpy array representing a grayscale image. Here is an example of how it looks: [[[120,120,120],[67,67,67]]...] Since it is a gray image, having every R, G, and B value the same is redundant. I am looking to create a new 2D array t ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Animate the background image with a float effect using jQuery's timeout feature to create an up

I'm having an issue with a set of elements that have background images applied to them. Specifically, I want the planets in the images (all except the first one) to move slightly up and then back down to create a floating effect. In my jQuery code, I ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

What is causing my checkboxes to deactivate other selections?

My checkboxes are causing a dilemma where changing the value of one checkbox sets all others to false. To address this issue, I am considering implementing a solution in my validate.php file that would only update the intended checkbox value. If this appro ...

``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point: Preview https://i.sstatic.net/zfzBU.jpg Code : <div class="container my-12 mx-auto"> <div className="flex flex-wrap "> {error ? <p>{error.message}</p> : null} {!isLoading ...

When moving the child grid layout, it often results in unintentionally moving the parent grid layout along with

Currently, I am utilizing React Grid Layout from this repository: https://github.com/STRML/react-grid-layout. My task involves creating a draggable parent div along with a draggable child div. While the functionality works smoothly for the divisions indiv ...

When using the each() function, the array shows a length of zero and does not

Although I am well-versed in PHP, my understanding of JQuery is lacking and I'm experiencing some difficulty with arrays. Despite researching numerous forum posts on the topic, I still can't seem to get it right. I believe I have an array struct ...

Using external scripts that require access to the DOM and window object within a Javascript/Node.js Azure Function: Best practices

I am attempting to integrate external JavaScript into an Azure Function that uses the JavaScript/Node.js flavor. The external JavaScript library I need to use, Kendo, relies on a DOM and a window. To achieve this, I initially experimented with JSDOM, but I ...

During the deployment of a ReactJS app, webpack encounters difficulty resolving folders

While developing my ReactJS app, everything ran smoothly on localhost. However, I encountered some serious issues when I tried to deploy the app to a hosting service. In my project, I have a ./reducers folder which houses all of my reducers. Here is the s ...

Extract a selection from a dropdown menu in ReactJS

I have multiple cards displayed on my screen, each showing either "Popular", "Latest", or "Old". These values are retrieved from the backend. I have successfully implemented a filter option to sort these cards based on popularity, age, etc. However, I am u ...

What is the method for obtaining a unique id that changes dynamically?

Having trouble accessing the dynamically generated ID in jQuery? It seems to work fine in JavaScript but not in jQuery. Here's an example of the issue: My jQuery code: var img = $("#MAP"+current_img_height); $("#map").css({'height': img.h ...

What is the best way to find unique characters along with their frequency in JavaScript?

Can you help me adjust this code in order to receive the desired output: "T-1 r-1 a-1 e-1 " (other characters are repeating. So no need to print the others) function checkUniqueCharacters() { var uniqueChars = []; var count = 0; var full ...

Instructions on creating the effect of rainwater cascading over text and spilling onto a webpage

Is it possible to make the rain flow over my text? Below is the code snippet from my JSFiddle: function strop(cleft, ctop, d) { var drop = document.createElement('div'); drop.className = 'punct'; drop.style.left = cleft + & ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...