Sorting arrays with nested objects in JavaScript

I am facing a challenge with sorting an array of objects in two specific ways:

  1. First, I need to sort the objects by alphabetical order using the country name.
  2. Then, inside each country, I have to arrange the scores in ascending order.

Below you can find the original array and the code snippet I attempted to use for this task.

//Array Structure
let allCountryScores=[
   {
      name: "Ethiopia", 
      scores:  [ {n: "Sub", s: 9990}, {n: "lucy", s: "4134234"}, {n: "DWH", s: 9999},  {n: "Hanif", s: 999999999} ]
    },     

]

//Code Attempt

//Sorting countries alphabetically
let orderedCountries = allCountryScores.sort((a, b) => a.name.localeCompare(b.name));
//Sorting scores numerically within each country
let orderedScores = orderedCountries.forEach(country => { country.scores.sort((a, b) => a.s > b.s) });
console.log(orderedScores);

When I check my console, it returns 'undefined'. Can anyone help me identify what might be causing this issue in my code?

Answer №1

There are a couple of issues to address:

  1. The use of forEach doesn't return any value, so there is no need for an assignment in that line. Simply remove it. Additionally, the assignment on the previous line isn't necessary either as sort modifies the array directly.

  2. The sorting logic for scores is incorrect. The expression a.s > b.s does not provide the expected result for the callback function of sort. Instead, you should use a.s - b.s to return the correct comparison result.

To resolve these issues and assuming modification of the original arrays is acceptable, here is an updated version:

//Sort countries alphabetically
allCountryScores.sort((a, b) => a.name.localeCompare(b.name));
//Sort scores numerically  
allCountryScores.forEach(country => { country.scores.sort((a, b) => a.s - b.s) });
console.log(allCountryScores);

If creating new arrays with new objects containing sorted arrays is desired, you can achieve it like this:

const countries =
    allCountryScores.map(({name, scores}) => {
        // Copy and sort the scores
        scores = [...scores].sort((a, b) => a.s - b.s);
        // Return a new object
        return {name, scores};
    })
    // Sort the new array of countries
    .sort((a, b) => a.name.localeCompare(b.name));

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

I have a JavaScript code that smoothly scrolls to different id's on a webpage, but I need assistance in adding an exception for a particular id

I'm looking to incorporate smooth scrolling for all hash links in my JavaScript. However, I need the id=nav and its resulting hash link, /#nav, to be exempt from this functionality as it interferes with the menu responsiveness. Can someone provide gui ...

Wrapping an array into a string in Laravel: a step-by-step guide

Is there a way to convert my return array into a string in Laravel? I would like it to look something like this: Laravel: $columnDefinitions = array(); $columnDefinition = new \stdClass(); $columnDefinition->label = "No"; $column ...

What techniques can I use to generate code dynamically for transferring an object to a different Node process?

I'm in the process of developing a node server that must execute potentially unsafe code. To ensure security, I am utilizing a Sandbox API that guards against attacks and provides results and outputs from scripts. This API employs a modified global ob ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...

Issue with passing multiple promises to $q.all function

Currently, I am attempting to iterate through an object and fetch data for each iteration from two separate service API functions. These functions return promises due to using the $http object, which means I must wait for the responses before populating my ...

jquery accordion set to collapse by default when the page first loads

Currently, I have integrated JQuery UI accordion into my webpage and I am facing a minor issue. Upon page load, all tabs are initially open for a few seconds before collapsing. I suspect this might be a loading effect. Any suggestions on how to ensure that ...

The React.js .map function encountered an error while trying to map the results from Firebase

As a newcomer to the realm of React and Firebase, I find myself struggling with arrays and objects. It seems like the way my data is formatted or typed does not play well with the .map method. Despite scouring Stack Overflow for answers, none of the soluti ...

"Utilizing Vue.js for frontend, this app utilizes axios from the client side, rather than

As a newcomer to the world of programming, I apologize if my question sounds basic. I currently have a setup where a Vue.js application is running on a Linux Red Hat server with Apache installed via XAMPP. Additionally, an ASP.NET Core 6 Web API applicatio ...

Execute a database query to search for patterns using Regular Expressions within the

As I embark on a new project, I find myself questioning my approach before diving in too deep and realizing it may not be the most efficient path. Within the realm of a large company where we develop unofficial tools for internal use, I am faced with limi ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Utilizing Mongoose Schema for CSV Import

My current task involves importing a large CSV file into a mongo DB, where the order of the values will determine the key for each entry in the database: Here is an example of the CSV file structure: 9,1557,358,286,Mutantville,4368,2358026,,M,0,0,0,1,0 9 ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

Combine the content from several URLs listed in an array using either the .get or .ajax method

Is it feasible to add the content of each URL in the array to a given container from a list of URLs using jQuery? For example: <li class="contacts"><a href="index.php#contact1">Contact 1</a> <li class="contacts"><a href="index. ...

Combining video.js and vue.js for seamless integration

Can anyone guide me on how to display a youtube video using a video.js player within vue.js? I'm new to integrations and not sure what it entails. Any assistance will be greatly appreciated. ...

Simple method to retrieve the ID of an input field within a form using jQuery selectors

I have a form with each input field having a unique id, and I have attached a jQuery 'input' event to the form. I want to retrieve the id of the field on which the user changes some value using a jQuery function. There seems to be something missi ...

Stopping the spread of popup alerts: A comprehensive guide

I'm having trouble explaining this in English;-) Whenever I select an option, an alert pops up for each choice and I don't know how to stop it. Step 1: Choose the "aaaa" option, for example 1111 alert ... Step 2: Choose the "bbbb" option, for ...

Common Mistakes when Working with Java Character Arrays

I'm currently working on a function to translate characters into their corresponding numbers, such as a=1, b=2 ... I've been receiving feedback from the IDE regarding my declaration of the dictionary array. Despite going through the documentatio ...

Search a location database using the user's current coordinates

Currently, I am working on a project that involves a database containing locations specified by longitude and latitude. Upon loading the index page, my goal is to fetch the user's location and then identify every point within a certain distance radius ...

What order should jquery files be included in?

Today I ran into an issue while trying to add datepicker() to my page. After downloading jqueryui, I added the scripts in the following order: <script type="text/javascript" src="js/jquery.js"></script> <script src="js/superfish.js">< ...

Download button on Rshiny platform for collecting numerous files from different sources

I am on a quest for knowledge regarding the inclusion of a download button in my application that consolidates various files into a zip archive. Within my application, there are a timeline and a datatable, with files linked to entries on the datatable. Th ...