Sorting arrays alphabetically based on another value in JavaScript

Maybe I'm not asking this question properly, but I can't seem to find the solution online.

I have an array of employees that I need to sort by different criteria like position or department.

There are several employees with similar values (such as multiple bartenders or guest services staff).

So, what I need is to group these employees (all bartenders or all guest service staff) and then sort them alphabetically by last name, and if needed, further sort them by first name within the same last name.

This is how my current sorting function looks:

  const sorted = state.employees.sort(function(a, b) {
    if (a[filterValue] === b[filterValue]) {
      let alphaA = a.lastName, alphaB = b.lastName;
      return alphaA < alphaB ? -1 : alphaA > alphaB ? 1 : 0;
    }
    return a[filterValue] > b[filterValue] ? 1 : -1;
  });

However, when I click on the sort functionality, the order changes each time, as shown in this GIF: https://i.sstatic.net/V3Pzv.gif.

Also, there isn't any logic for ascending/descending order, so clicking multiple times should ideally give the same sorted array instead of different orders every time.

I suspect the issue might be with how the alphabetical comparison is handling the matching values within the same subgroup (like all employees in accommodations department), but I'm unsure and need help resolving it.

I would appreciate assistance in completing this task, along with an explanation as I'm still trying to grasp how sorting functions work.

Thank you!

Answer №1

let filter = 'department' // just a placeholder for now


state.employees.sort(function(a, b){
    if (a[filter] > b[filter]) return 1;
    if (a[filter] < b[filter]) return -1;
    
    if (a.lastname < b.lastname) return -1;
    if (a.lastname > b.lastname) return 1;
    
    if (a.firstname < b.firstname) return -1;
    if (a.firstname > b.firstname) return 1;
    
    return 0;
});

Check out my example here: https://jsfiddle.net/zjhs20vz/

If I understood your question correctly, sorting based on this hierarchy of filters seems logical—starting with sorting filters, then by last name, and finally by first name.

Answer №2

Instead of creating your own comparison function, you might want to consider utilizing an existing library such as thenBy. This library allows you to arrange items by multiple criteria using a syntax like:

state.members.sort(firstBy('position').thenBy('lastName').thenBy('firstName'));

You will need to adjust it to suit your specific requirements and reset the orderings as needed, but it can save you the trouble of developing your own custom solution.

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

Sentry platform is failing to record network-related problems

Incorporating Sentry into my Next.JS application has allowed me to easily detect JavaScript errors such as reference or syntax issues on the Sentry platform. Unfortunately, I have encountered some challenges as Sentry is not logging any network-related er ...

Exploring the Use of data- Attributes in SVG Circle Elements

Looking for a way to dynamically update the color of a Circle element in your SVG when it is clicked? You can achieve this by using jQuery's .css() method in conjunction with the data-* attribute. CHECK OUT AN EXAMPLE: STYLING IN CSS svg { height ...

Only one condition is met when using the Javascript if statement with the :checked and .bind methods

I need help creating an Override Button to disable auto-complete for a form using Javascript. I want the div "manualOverrideWarning" to display a warning if the button is selected, but my current function only works the first time the user presses the butt ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

What could have caused the lack of output from the render function?

I've been working on generating my navigation drawer from JSON data and have everything functioning using components. Now, I'm in the process of refactoring to functions for better performance and to enhance my knowledge of React and JavaScript. ...

What is the method to convert a single object into an array of multiple objects?

Is there a way to convert this into an array of objects that are ordered based on another array's keys? { tom: 11, jim: 22, jay: 13 } Here are some input -> output examples: ['jim', 'tom', 'kim', 'jay&apo ...

Attempting to modify text using the header parameter has proven to be ineffective

pages/_middleware.ts import { NextRequest, NextResponse } from 'next/server'; const isMobile = (userAgent: string) => /iPhone|iPad|iPod|Android/i.test(userAgent); const propName = 'x-rewrite'; enum Device { desktop = 'no& ...

Is there a way to customize the JavaScript click event for specific elements only?

I've been following a tutorial from codrops where each item has a hover event and a click event that triggers an anime.js function. My goal is to prevent certain items (grid cells) from triggering the anime.js function when clicked, while still allow ...

Animating the starting angle of an arc using d3.js

I'm looking to animate the starting angle of an arc using D3.js. If anyone has any tips or helpful links, I would greatly appreciate it! Here's what I've already attempted: http://jsfiddle.net/87e3d4tj/ d3.select('#my-path').da ...

Trigger a JavaScript popup when a link is clicked

I need assistance with creating a pop-up for a link on my website. The code for the pop-up should be as follows: <script data-cfasync=false src="//s.ato.mx/p.js#id=8135&type=popup&size=800x600&hourscap=1"></script> Here is an exam ...

Alerts are essential for the proper functioning of the AJAX function. Without them

As I incorporate a substantial amount of AJAX with XML Http Requests on my website, I encounter a peculiar issue with a few random AJAX calls. There seems to be an execution problem within my JavaScript code in the onreadystatechange function where certain ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

Calculate the mean of every group of 20 numbers within an array

In my coding dilemma, I am faced with a large array (consisting of over 400 numbers) called decimal[] Raw. The task at hand is to calculate the average of every set of 20 numbers within this array and populate a new array or list named RawAvgList. Subseque ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Is it advisable to substitute setTimeout with node-schedule in a node.js environment?

How can I prevent players from entering a raffle between 11:55pm - 11:59pm every Thursday? I attempted to use node-schedule to block access during this time frame by scheduling it to run every second, but unfortunately, I was still able to access the route ...

Streamlining the creation of JavaScript/ECMAScript array literals

Currently in the process of developing a JavaScript/ECMAScript 5.1 parser using JavaCC and encountering challenges with the ArrayLiteral production. ArrayLiteral : [ Elision_opt ] [ ElementList ] [ ElementList , Elision_opt ] ElementList : ...

At what location do promises execute their callbacks?

When the callbacks of then, catch, or finally are ready to be executed, where do they run? I recently read on Stack Overflow that these callbacks are executed in the call stack of the main JS thread (due to JavaScript being single threaded). If this is a ...

Error: Trying to dispatch from an undefined property in Angular and Redux

In the process of developing a Shopping app using Angular + Redux, I encountered an issue. When attempting to trigger the "ADD_PRODUCT" action on click through a dispatcher function, I keep running into the error message: ERROR TypeError: Cannot read prop ...

Can an array be created with a variable number of elements?

When faced with the need to create an array with a variable number of elements at runtime, I follow this approach. int n, i; printf("Enter the number of elements: "); scanf("%d", &n); int myArray[n]; for(i = 0; i < n; i++) myArray[i] = 0; Howe ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...