Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty.

//Declare Variables
var TN = ['Chattanooga', 'Nashville', 'Memphis'],
    FL = ['Tampa', 'Miami', 'Orlando', 'Clearwater'],
    GA = ['Atlanta', 'Marietta'];



//Create a function to sort arrays from most to least items
function sortStates(a, b){
    return a - b;
}


//Create an object to store the total items in each array 
var stateTotal = {
        totalTN: TN.length,
        totalFL: FL.length,
        totalGA: GA.length
};

//Sort states in descending order based on the number of items
stateTotal.sort(sortStates);

console.log(stateTotal);

Expected Output:

totalFL: 4, totalTN: 3, totalGA: 2

Answer №1

Objects do not have the ability to be "sorted", unlike arrays which can be sorted.

Are you working on a specific task or assignment? The instruction to

Create an object to get total in each array
seems unclear.

Nevertheless, here is a code snippet to demonstrate the sorting of states based on their total count:

//Define Arrays
var TN = ['Chattanooga', 'Nashville', 'Memphis'],
    FL = ['Tampa', 'Miami', 'Orlando', 'Clearwater'],
    GA = ['Atlanta', 'Marietta'];

//Function to sort arrays in descending order
function sortStates(a, b) {
    return b.total - a.total;
}

//Create an object to store the total count of elements in each array
var stateTotal = [
    { name: 'totalTN', total: TN.length },
    { name: 'totalFL', total: FL.length },
    { name: 'totalGA', total: GA.length }
];

//Sort the states based on total count
stateTotal.sort(sortStates);

stateTotal.forEach(info => {
  console.log(`${info.name}: ${info.total}`);
});

Answer №2

The most effective method for sorting states by the length of their towns is

var states=[];
states.push({
    name:"NY",
    towns:['New York City', 'Albany', 'Buffalo']
    });
states.push({
    name:"CA",
    towns:['Los Angeles', 'San Francisco', 'San Diego']
    });
states.push({
    name:"TX",
    towns:['Houston', 'Dallas', 'Austin']
});
states.sort((state1,state2) => state2.towns.length - state1.towns.length).forEach( state => console.log(`Total ${state.name}: ${state.towns.length}`));

Answer №3

When working with objects and arrays, it can be easy to get confused. Arrays, denoted by [], can be sorted, but object properties are not sorted.

//Defining Variables
var myData = {TN:['Chattanooga', 'Nashville', 'Memphis'],
              FL:['Tampa', 'Miami', 'Orlando', 'Clearwater'],
              GA:['Atlanta', 'Marietta']};

var keys=Object.keys(myData);

var mySort=[];
for(key in keys){
   mySort.push([keys[key],myData[keys[key]].length]);
}

mySort.sort(function(a, b){
    return b[1] - a[1];
});

myObj={};

for(let i=0;i<mySort.length;i++){

myObj["total" + mySort[i][0]] = mySort[i][1]

}

console.log(myObj);

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

Arranging Controls in a Grid in a Vertical Formation?

I have a Paper element with checkboxes in it. Here is the image of what I am talking about: https://i.stack.imgur.com/Epmk5.png Currently, the checkboxes are arranged horizontally, but I want them to be stacked vertically. The Paper element containing the ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

The Vue.js application appears to be functioning properly with no error messages, however

Currently, I am in the process of learning Vue. Recently, I came across a helpful tutorial that I've been trying to implement using the standard vue-cli webpack template by splitting it into single file components. Despite not encountering any errors ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

React: The issue with async and await not functioning as expected when using fetch

I am working with an API on a Node server that returns JSON data like this: {"result":[{"ProductID":1,"ProductName":"iPhone10","ProductDescription":"Latest smartphone from Apple","ProductQuan ...

I'm experiencing a flickering issue with my carousel when it reaches over 10,000 pixels during animation. Could this be related to a jQuery problem

After my carousel moves past 10000 pixels, it starts flickering through multiple elements. I'm utilizing jCarousel Lite: Could this be a jQuery-related issue? My initial assumption is that it may be specific to jCarousel Lite, but there doesn't ...

What is the reason for the find() method not displaying the most recent data from a MongoDB database in an Express.js application?

Upon calling the app.post('/form-submit', funtion(req, res)) method, my expectation is for it to first save the data using save(). This works fine, but then when I call the find() method, it shows all the data from the mongoDB database except for ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

What is the recommended placement for the implicitlyWait method in Protractor?

When implementing implicitlyWait, what is the appropriate location to include browser.manage().timeouts().implicitlyWait(5000); within the test script? ...

Enhance the annotation of JS types for arguments with default values

Currently, I am working within a code base that predominantly uses JS files, rather than TS. However, I have decided to incorporate tsc for type validation. In TypeScript, one method of inferring types for arguments is based on default values. For example ...

Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test. caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true) driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps) drive ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

Searching in a PHP 4 level deep multidimensional associative array for a specific value

Hey everyone! I have this multidimensional associative array and I'm looking to search within it. public static function userAccessArray() { return array( array( 'title' => 'General', 'ac ...

Step-by-step guide for embedding a Big Commerce website into an iframe

Can a website be opened inside an iframe? If not, is it possible to display a message like 'page not found' or 'this website does not allow data fetching in iframes'? <!DOCTYPE html> <html> <body> <h1>Using the ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

What is the best way to incorporate options using jQuery?

Currently, I am incorporating a jQuery plugin for modals into my website. The plugin/code offers the functionality to customize the background color of the modal. For more details on how to do this, you can visit the plugin's official website. Althou ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...