What is the best way to organize an array both alphabetically and by the length of its elements?

Imagine I am working with an array like this: ['a', 'c', 'bb', 'aaa', 'bbb', 'aa']. My goal is to sort it in the following order:

aaa, aa, a, bbb, bb, c.

this.array= this.array.sort((n1, n2) => n1.localeCompare(n2));
this.array= this.array.sort((n1, n2) => n2.length - n1.length);

However, this approach is not yielding the desired result. How can I correct it?

Answer №1

To determine if one string starts with another, you can compare the lengths of the strings.

var array = ['a', 'c', 'bb', 'aaa', 'bbb', 'aa'];

array.sort((a, b) => {
    let d = a.startsWith(b) || b.startsWith(a)
            ? b.length - a.length
            : 0;

    return d || a.localeCompare(b);
});

console.log(array);

If String#startsWith is unavailable:

var array = ['a', 'c', 'bb', 'aaa', 'bbb', 'aa'];

array.sort((a, b) => {
    let min = Math.min(a.length, b.length),
        d = a.slice(0, min) === b.slice(0, min)
            ? b.length - a.length
            : 0;

    return d || a.localeCompare(b);
});

console.log(array);

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

The download attribute in HTML5 seems to be malfunctioning when encountering a 301 Moved Permanently

I am attempting to create an automatic download feature for a file from a URL with a 301 Moved Permanently redirection. Here is the current code: <a href="myserverapi/download?fileId=123" download="image.jpg" target="_blank" ...

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

What is the functionality of named function expressions?

After coming across an intriguing example in the book labeled as a "named function expression," I was curious to delve into its mechanics. While the authors mentioned it's not commonly seen, I found it fascinating. The process of declaring the functi ...

Encase a group of child elements within a parent container using

Currently, I am able to wrap an entire li-element in an ordered list with a link: $(e).wrap('<a href="#" onclick="window.open(\'/xyz/\');return false;"></a>'); This is the HTML construct: <li class=""> ...

What is the reason for my result showing as Object { } rather than MyObj { }?

When utilizing the web development tools console, if a browser object is typed, it will return as "console." > console Console { } > console.log(console) undefined > Console { } This behavior applies to all browser objects. However, when I try ...

Revise the validation process for the drop-down menu and input field

Looking for help with text field validation based on a dropdown selection. There are two scenarios to consider: 1. User changes dropdown value and then enters text in the field. 2. User enters text in field and then changes dropdown. I've written cod ...

Connect your Angular2 app to the global node modules folder using this link

Is there a way to set up a centralized Node modules folder on the C disk instead of having it locally within the app directory? This would be more convenient as Angular2 CLI tends to install over 125mb of Node modules in the local folder. In our TypeScrip ...

Iterate through a JavaScript array to access objects with varying IDs

Struggling to navigate the JSON data due to ID 29450 and 3000 out of a total of 1500 IDs in the database. Looking to log the information ['Id', 'Description', 'StartDate'] for both IDs. Feeling a bit stuck, hoping someone can ...

Enhance Your jQuery Experience with Advanced Option Customization

I am currently developing a plugin that deals with settings variables that can be quite deep, sometimes reaching 3-4 levels. Following the common jQuery Plugin pattern, I have implemented a simple method for users to update settings on the go using the not ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

Conditional return type mistakes

I'm facing an issue with a function that takes a parameter "value" and is supposed to return 0 or 1 based on its true or false value. Check it out here. const f = <T extends boolean>(value: T): false extends T ? 0 : 1 => { if (value === ...

Best Practices for Updating UI State in Client Components Using NextJS and Server Actions

My goal is to create a page using nextjs 14 that functions as a stock scanner. This page will retrieve data from an external API using default parameters, while also offering users the ability to customize parameters and re-run the scan to display the resu ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

Issues with data retrieval from PHP file in AJAX submission

During my attempts to utilize AJAX for submitting data to a PHP file, I encountered an issue where the submission was successful and I could receive a message echoed back from the PHP file. However, when trying to echo back the submitted data or confirm if ...

"Troubleshooting: Why isn't my jQuery AJAX POST request successfully sending data to

Here is the jQuery code snippet that I am currently working with: $("#dropbin").droppable( { accept: '#dragme', hoverClass: "drag-enter", drop: function(event) { var noteid = "<?=isset($_POST['noteid']) ? ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

What is the best method for extracting html-string from html-string across different browsers?

Works perfectly in Chrome and FF, but encountering issues with Safari. var content = '<div><span><p>Can you catch me?</p></span></div>'; content = $.parseXML(content); var span = $(content).find('span&apo ...

Using an array.map inside a stateless component with React.createElement: the type provided is invalid

There is a component called BasicDetail in my code with the following structure: import React from "react"; import { Grid, Form } from "semantic-ui-react"; const BasicDetail = ({DetailData}) => { return( <div> <Grid.Ro ...

The functionality of the JavaScript click function is limited to a single execution

In my dropdown menu, I have a submit function that triggers whenever any children of the dropdown are clicked. However, I now need to exclude a specific li element from this function because it requires inserting a tracking ID in a popup iFrame. The code ...