Organize an array containing nested objects within other objects

I'm stuck with sorting this array:

[
  ["name1", { count: 20 }],
  ["name2", { count: 10 }]
]

Is there a way to sort this array based on the count values?

My attempt using the sort function was unsuccessful,

const sort = Array.sort((a, b) => b.count - a.count);

Unfortunately, this didn't have any effect.

Answer №1

To retrieve the second entry in the arrays within the outer array, you should use a different approach in your code. The issue lies in attempting to access a count property on the array entries, which they do not possess:

theArray.sort((a, b) => b[1].count - a[1].count);

It's important to note that the sort function is called directly on the array itself, not on the Array constructor. Additionally, this function sorts the array in place rather than returning a sorted version (although it does return the same array).

Here's a live example to illustrate:

const theArray = [
  ["name1", { count: 20 }],
  ["name2", { count: 10 }],
  ["name3", { count: 15 }]
];
console.log("Before sorting:", theArray);
theArray.sort((a, b) => b[1].count - a[1].count);
console.log("After sorting:", theArray);
.as-console-wrapper {
    max-height: 100% !important;
}

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

Iterate through each image within a specific div element and showcase the images with a blur effect applied

I have a div with multiple images like this: <div class="am-container" id="am-container"> <a href="#"><img src="images/1.jpg"></img></a> <a href="#"><img src="images/2.jpg"></img>< ...

Swap out the variables in your function with the values selected from the dropdown menu

I've recently started delving into writing JS functions and I'm facing a challenge with the following scenario: On an HTML page, I want to change a variable within a lodash function based on the value of a dropdown and display the result in a HT ...

Using jQuery, JavaScript, and PHP, we can easily implement the functionality to disable the form and submit button

After submitting a form, I am trying to disable both the submit button and the form itself. However, every solution I have attempted either disables the form and button without submitting it or submits the form without disabling the button/form. This is t ...

Executing Scripts inside an iFrame in Angular

Upon receiving an API response, I am presented with HTML as a string. Inside this HTML are internal script tags that contain functions called under $(window).load(). How can I successfully load this HTML within my Angular app? I attempted to append the HT ...

How can I convert the content of a file into a byte array

Is there a way to store text contents (String) directly into byte arrays without creating various file types like txt, pdf, xml, or html? Currently, I create the file, convert it to a byte array, and then delete it. It's a lengthy process and I' ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...

Generating a fresh array by extracting values from an existing array in a loop

I am currently working with an array of strings named groups and I am using a forEach loop to iterate through it. My goal is to create a new array where each string becomes the name of the array. I attempted to initialize the arrays with let [group] = [], ...

Is it feasible to insert the result of a JavaScript code into a PHP script?

Alternatively, you can view both codes side by side on the panelbackup(dot)com/codes page Alright, I have a code placed on page 1.html that adds four random numbers at the end of any given URL: <head><script>window.onload = function() { ...

The nested switch statement encountered an ArrayIndexOutOfBoundsException with a negative index of -4

Below is the code I have provided for your reference. When attempting to run the code for the multiplication functionality, I encountered the following error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -4 at choice2.main(choi ...

What is the best way to pass data from the server to a Vue CLI application?

I am looking for a way to connect my Vue CLI app to a server back-end. The server will send a view template along with data payload, and I need to inject that payload as JSON into the Vue app as a data property. Here is a snippet of the index.html file ge ...

Numerous asynchronous AJAX requests accompanied by various loading indicators

My ASP.net MVC page is utilizing ajax calls to load data for each of the six divs. To handle the loading indicator, I have created two methods as shown below. $("#divId").loading(); $("#divId").stopLoading(); Here is an example of one of my ajax calls ( ...

Use jquery to create animated progress bars in various designs

I am attempting to create an animation in JavaScript for multiple Bootstrap progress bars, each based on their individual widths. However, I have encountered an issue where the code only takes the value of the first DOM element with the class "progress-bar ...

Node.js seems to be having trouble with emitting events and catching them

I'm having trouble troubleshooting my code. // emitter.js var EventEmitter = require('events').EventEmitter; var util = require('util'); function Loadfun(param1, param2, db){ function __error(error, row){ if(error){ ...

Adding the elements of a Fortran 77 array

Trying to develop a program that can minimize chi-squared for a four-parameter least squares fit is proving to be more challenging than expected. Lately, I've been facing multiple issues with the subroutine call-ins resulting in three recurring proble ...

Unable to retrieve the corresponding row from the Yii model

Currently, I am facing an issue with fetching the related row based on user input while using select2. I am referring to a tutorial (link provided) on how to achieve this but I seem to be stuck at retrieving the matched row. The following code snippet show ...

Increasing the checkout date by one day: A step-by-step guide

I am looking to extend the checkout period by adding 1 more day, ensuring that the end date is always greater than the start date. Below are my custom codes for implementing the bootstrap datepicker: $(function() { $('#datetimepicker1').da ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

Can an image be scanned pixel by pixel to extract and store each pixel's color in an array mapped by its coordinates?

Currently, I am working on a browser game where I have created a pixel map as a coordinate system. Each color on the map represents a unique terrain type with specific values that impact different aspects of the game. I'm looking for a solution using ...

Error: The absence of an element identified by the locator does not cause the protractor spec to fail, but rather it executes successfully

This automation framework follows the page object model and utilizes the async/await approach rather than promises. TypeScript is used, with compilation to JavaScript (protractor) for script execution. Page Object: async addProjectDetails(): Promise< ...

Excessive delay in executing Javascript loops

While developing an EMI calculator for a hybrid mobile app, I encountered a performance issue. The execution within one of the loops takes too long, resulting in the page becoming unresponsive. Here is my code snippet: var EMICalculator = { basicEMI: fun ...