Implementing Reverse Sorting Feature with a Second Click in JavaScript

I've implemented a function that successfully sorts a JSON array when a link is clicked (the function is triggered by an onclick event). Here's the current sorting function in action:

function sortArch(a, b) {
    x = eval("a." + sort_type).toLowerCase();  
    y = eval("b." + sort_type).toLowerCase();  
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

Now, I want to modify the function so that when the same button is clicked again, it will perform a reverse sort. Reversing the sort order is straightforward:

x = eval("a." + sort_type).toLowerCase();  
y = eval("b." + sort_type).toLowerCase();  
return ((x < y) ? 1 : ((x > y) ? -1 : 0));

However, my challenge lies in ensuring that the function "knows" which way it needs to sort. I've considered using a boolean flag, but haven't been able to find a solution that actually works. I just need a reliable method to keep track of the current sorting direction and then apply the appropriate sorting logic when the button is clicked for the second time. Appreciate any assistance on this matter!

Answer №1

Here is a simple way to achieve this:

function customSort(descending) {
  var modifier = descending ? -1 : 1;
  return function(a, b) {
    var lowerCaseA = a[sort_type].toLowerCase(), 
        lowerCaseB = b[sort_type].toLowerCase();
    return lowerCaseA > lowerCaseB ? 1 * modifier : lowerCaseA < lowerCaseB -1 * modifier : 0;
  }
}

arr.sort(customSort(true)); // sort in descending order
arr.sort(customSort(false)); // sort in ascending order

By the way, it's best to avoid using eval whenever possible as it can slow down and complicate your code.

Answer №2

Just one more step to go:

function customSort(sortType, isAscending) {
    var direction = isAscending ? 1 : -1;
    return function(valueA, valueB) {
        var x = valueA[sortType].toLowerCase();
        var y = valueB[sortType].toLowerCase();

        return direction * x.localeCompare(y);
    }
}

Here are some examples of how you can use it:

people = [
    {firstName: 'Alice', lastName: 'Smith'},
    {firstName: 'Bob', lastName: 'Johnson'}
];


// Utilize the customSort function in your button click events:
people.sort(customSort('firstName', true));
// or
people.sort(customSort('firstName', false));
// or
people.sort(customSort('lastName', true));
// or
people.sort(customSort('lastName', false));

Cheers to sorting efficiently!

Answer №3

Your suggestion to utilize a boolean flag is highly recommended:

function arrange(inverted){
  if(inverted){
    //inverted sort code
  }else{
    //regular sort code
  }
}

button.onclick = function(){arrange(true);}; //or utilize addEventListener

This approach also facilitates a sort() class, which automatically performs a regular sort since undefined is considered "falsy".

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

Invoke the function defined within a modal when dismissing a ui-bootstrap modal

Inside my ui-bootstrap modal controller, I have a $watch function set up for a variable. The code snippet looks like this: main.controller('modalCtrl', ['$scope', '$rootScope', '$modalInstance', function ($sc ...

Adjust the image size without losing sharpness

I'm currently working on a web application for Minecraft and I am looking for a way to resize someone's skin without losing quality. I believe javascript might be the solution to this issue. ...

Issue with Phong material not responding to area light in a three.js.obj model

Trying to incorporate both a phong material and a shader area light onto my .obj model has proven to be problematic. I attempted using an array within Meshface material to load both materials, but the model vanishes completely when both are applied simulta ...

Navigating the loading of information with fetch and React Hooks

As a newcomer to React and still learning JavaScript, I am facing a challenge with handling useEffect alongside an asynchronous function. My goal is to fetch data from an API and render a quote in the paragraph with id of text, along with the author's ...

Click on the marker to adjust the map's central position

I've successfully created a leaflet map featuring an array of 3 different locations, each marked with a popup window. Now, I'm looking to implement the functionality that will allow the center of the map to change dynamically when a user clicks o ...

How can I dynamically update the value of an ng-option based on the selection of another ng-option?

My application has 2 select option boxes. The first box contains a list of countries, and I want the second box to update its values based on the selection made in the first box. For instance, if I choose India from the first select box, the second select ...

What is the process of deserializing this?

{ "success": true, "time": 1668509701, "currency": "RUB", "items": { "186150629_143865972": { "price": "278.61", "buy_order": 251.72, &q ...

Issue with Laravel 5.4: AJAX behaving unexpectedly and not returning errors as it should

After going through several tutorials on handling AJAX requests in Laravel, I'm still facing some issues. Each tutorial has its own approach... Finally, one method is not giving me a 500 error, but it's not displaying validation errors as expect ...

Update the JSON data label

When I receive a category list, it looks like this: 0: name: "Acessórios para Veículos" uuid: "d87506-bb-08-d0-58c2d4af" 1: name: "Agro, Indústria e Comércio" uuid: "d87507-bb-07-d0-57c2d4af" However, the component I am using does not recognize the n ...

In Python, when using the json.loads function, you may encounter a <class 'exceptions.ValueError'> error message like this: "Expecting property name: line 1 column 3 (char 2

Currently, I'm developing a python CGI script that is meant to receive a JSON string as input and process it accordingly. However, during testing, I keep encountering ValueErrors, and the cause behind them remains unclear to me. Here's an exampl ...

What is the most effective way to use checkboxes to apply multiple filters to an array of objects?

Let me simplify the description. Within the App component, I fetch data from a JSON file and store it in the flightsList array. My goal is to filter this array based on checkboxes selected in the FlightOptions and Airlines components. The issue that I&a ...

Angular API data causing an undefined error in the template

When attempting to display values in an HTML template from API data, I encountered an issue. Despite not defining all the values in the object, the data is displayed correctly. However, an error appears in the console: TypeError: Cannot read property &ap ...

The TextArea element is experiencing issues with the Jquery function

In my asp.net web application, I have implemented a JQuery function to restrict user input characters. $(document).ready(function () { $('input').on('input', function () { var c = this.selectionStart, ...

Customize Material-UI icons dynamically by changing their props in an array

I am looking to change props (color, size) for multiple icons in an array using Material-UI v4: const ICONS_ARRAY: React.ReactNode[] = [ <AlertCircleCheckOutline />, <AppleSafari />, <MotionPlay />, <AppleKeyboardCommand />, <Fil ...

Creating a GWT-compatible solution for implementing the Google Visualization - Annotation Chart

I am currently using the newly launched Annotation Chart in GWT by integrating native JavaScript. I have managed to display the example chart successfully, but unfortunately, it lacks interactivity and behaves more like an image. Can anyone provide guidanc ...

What is the alternative method to obtain dynamically added options without relying on the on change or onclick event?

I have a dynamic country select box where options are added on click, but I am having trouble accessing all the options in the select box with JavaScript. When I console log the select box HTML after appending the options, I only see the originally added o ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Navigating the loop in Vue using JavaScript

I'm facing an issue where I need to send data at once, but whenever I try sending it in a loop, I end up getting 500 duplicate id status errors. I have a hunch that if I click on something in JavaScript, the data might be sent all at once. assignment ...

The error message "There is no defined window.matchMedia prefers-color-scheme window in Next.js"

I am currently working on a project with React.js alongside Next.js and encountered an issue that I need assistance with. Upon loading the page, I need to set a variable that indicates whether the user is using dark mode or not. I attempted the following ...