The Array.sort method is limited to sorting based on a single criterion

I'm attempting to sort items first by their values and then alphabetically if they have the same value.

function order(a, b, total) {
    if (total == 0) {
        return a.localeCompare(b)
    } else {
        return total;
    }
}

var thingsArr = {"lamp":2, "books":2};

Object.keys(thingsArr).sort(function (a, b) {
    order(a, b, thingsArr[b] - thingsArr[a])
});

Why doesn't the else statement inside the function order handle alphabetical sorting of the resulting array when the if part handles sorting based on highest value? It only works correctly when used separately. What am I missing here?

Answer №1

Remember to always include a return statement within the sort function!

function organizeList(item1, item2, totalItems) {
    if (totalItems == 0) {
        return item1.localeCompare(item2);
    } else {
        return totalItems;
    }
}

var itemsArray = {"table":4, "pencils":6};

const sortedList = Object.keys(itemsArray).sort(function (item1, item2) {
    return organizeList(item1, item2, itemsArray[item2] - itemsArray[item1]);
});

console.log(sortedList);

Answer №2

If you are looking to organize a list of names in a more structured way, one approach could be to enhance the clarity by relocating the total calculation within your ordering function as shown below:

const items = {"lamp":2, "books":2}; 

function sortItems(a, b) {
    const total = items[b] - items[a];
    if (total === 0) {
        return a.localeCompare(b)
    }
    return total;
}

Object.keys(items).sort(sortItems);

However, if your intention is to utilize the list as keys for referencing your items, it might be beneficial to consider mapping them to an array of objects like { name: "lamp", qty: 2 } or tuples [ "lamp", 2 ] as illustrated below.

const items = {"cupboard": 0, "lamp": 2, "books": 2};

function mapValuesToObject([name, qty]) {
    return {
      name,
      qty,
    };
}

function sortItems(a, b) {
    const total = b.qty - a.qty;
    if (total === 0) {
        return a.name.localeCompare(b.name)
    }
    return total;
}

Object.entries(items).map(mapValuesToObject).sort(sortItems);

This will give you the following result:

[
  { name: 'books', qty: 2 },
  { name: 'lamp', qty: 2 },
  { name: 'cupboard', qty: 0 }
]

I hope this explanation proves to be useful. Keep up the good work!

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

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Where is the session management functionality situated within an OAuth-enabled web application?

When creating an oauth service (such as for Facebook or Gmail) enabled web application using Angular or React, where should session management be located? Should user sessions be maintained on the hosted server or within the oauth service itself? This is ...

What is the process for making a POST request with the Google Chrome Puppeteer library?

Hello everyone, I'm currently attempting to make a POST request using the puppeteer headless chrome library. I'm running into some issues with the code below and can't seem to figure out what's wrong. // Obtain the csrf token ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Struggling with a 400 Bad Request Error in Angular with WebAPI Integration

I've been working on creating a database to keep track of comics, and so far I can successfully add new comics and retrieve them using GET requests. However, I've hit a roadblock when trying to update existing comics using PUT requests. Every tim ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' https://i.sstatic.net/3KRMQ.png The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to ...

extracting the value of a chosen radio button in AngularJS using HTML

When attempting to retrieve the selected value from a radio button, I am encountering an issue where choosing "teacher" still shows as "student." Here is the HTML file: <!DOCTYPE html> <html ng-app="phase2"> ... (HTML code continues) Rige ...

Error in AngularJS: The argument 'fn' is not a function and is undefined

I'm encountering an issue with AngularJS 1.6, and the error message is stating: Error: [ng:areq] Argument 'fn' is not a function, got undefined I suspect the problem lies within my testService, and I'm seeking assistance in identify ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

Tips on incorporating character frequency counting in a string with JavaScript

I am working on a simple project involving HTML code. <textarea id="text" placeholder="Type text...."></textarea> <a id="button" class="button"></a> <textarea id="result" disabled></textarea> Additionally, I have a blo ...

Incorporate live data into a sample chart.js file within a Django template

I'm currently using the "start bootstrap4" template in my Django project. I need to customize the data displayed in a chart contained within the template by modifying the chart-pie-demo.js file. In my views.py file, I have defined the data that I wan ...

Configuring vue-jest: Does anyone know how to set up aliases for template/script src attributes in Vue?

Dependencies: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue-jest": "^3.0.7" I am dealing with an application that utilizes an alias (referred to as "foo") de ...

I seem to be in a predicament. It appears I must tweak the loops in order for them to effectively compare my two arrays without outputting unnecessary characters

I am currently working on a program where I need to compare two string arrays. The goal is to swap the case of characters in one array if they match any character in the other array. However, despite my efforts, I keep getting unexpected output. Here is w ...

Using AngularJS ng-src within an Iframe

I have been trying to dynamically set the source of an iframe using a scope variable, but it keeps appearing blank. Here is what I attempted: <div ng-repeat="url in urls"> <div ng-click="testAlert(url.domain)"> <iframe ng-src="{{ url ...

Issue with dropdown component in material ui version v1.0 beta 26 encountered

Currently, I am encountering an issue with the dropdown component while using Material UI v1.0 beta.26. In this updated version, you are required to utilize the Select component along with MenuItem. Although my dropdown is successfully populated upon rend ...

Switching script code to composition API(setup) in Vue3

I have implemented the code below in a page. <script> export default { name: 'FaqSection', props: { content: { type: Object, required: true, }, }, data() { return { scrollArgs: { behavior: &apos ...

Having trouble updating state following a fetch request in React Native

I'm encountering a strange problem when attempting to update the state object value after making a GET request using either fetch or axios (neither are working). I have tried various solutions I found online, but none of them seem to be effective. Be ...

looping through a collection of objects with partially distinct attributes

How can you iterate over an array of objects to retrieve the results of every previous game played? I encountered difficulties while attempting to iterate over non-existent values. The desired result is an array structured like this: newArr: [ { ...

Using `window.location.href` will terminate any pending asynchronous calls to the API

Before all async calls to the API are completed, window.location.href is triggered when the code runs. Setting a breakpoint on the location resolves the issue. How can I ensure that all calls are finished before invoking window.location.href? Code: const ...

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...