Rearranging an array while preserving the initial sorting order

My challenge involves handling an array of employee information that is organized by comparing the subdepartment of each employee to the priority of subdepartments within a particular department.

When a user clicks on an employee's name in an index, the system uses their department (stored as a data attribute) to retrieve all other employees in the same department. This collection is then sorted based on the manual assignment of subdepartment priorities in another array.

var results = $.grep(data, function(employee) {
    if(employee.DEPT == dept) {
        return employee.DEPT = dept;
    }
});

// ** PLEASE NOTE: 'deptorder' is "Department" : [ "Subdepartment1", "Subdepartment2" ] defined manually
// Choose the order of subdepartments based on the department
order = deptorder[dept];

The initial sorting process:

results.sort(function(a, b) {
    return $.inArray(a.SUBDEPT, order) - $.inArray(b.SUBDEPT, order);
});

After the initial sort, I need to structure the employees within each subdepartment group. The goal is to identify a 'manager' and have them displayed first within the grid for that specific subdepartment. Subsequently, other employees can be arranged alphabetically or using any other criterion.

I am seeking advice on how to perform a second round of sorting to achieve this desired outcome. Currently, managers are distinguished by having an employee.MANAGER attribute set to '1', while others have it blank.

I attempted the following approach:

results.sort(function(a, b) {
    return (a.MANAGER == 1) - b;
});

Unfortunately, this method did not yield the expected results. The sorting mechanism described above represents my limited experience with employing the sort function. Any guidance would be greatly appreciated!

Answer №1

To streamline the process, you can consolidate all comparisons into a single .sort() iteration:

results.sort(function(a, b) {
  if (a.DIVISION == b.DIVISION) {
    if (a.MANAGER == 1)
      return -1; // prioritize a
    if (b.MANAGER == 1)
      return 1; // prioritize b
    return 0; // or compare names
  }
  return $.inArray(a.DIVISION, order) - $.inArray(b.DIVISION, order);
}

In essence, during the sorting process, when comparing two elements within the same division, it's crucial to check if either one is the manager. The managerial entity should be placed ahead of the other. However, if they belong to distinct divisions, their departments are the only relevant factor.

If both individuals share the same division and neither hold a managerial position, further comparison can then be based on name or any preferred criteria.

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

Declare webpage as manager for mailto links

One interesting feature I've observed in various web-based email providers is the ability to add the website as the default mailto links handler in browsers like Firefox and Chrome. This means that when clicking on a mailto: link, it will automaticall ...

The V-model fails to reflect changes when the checkbox list is updated

I am facing an issue with my checkboxes that are generated dynamically in a component using a v-for loop. Once a checkbox is checked, it is added to an array of selected checkboxes. The problem arises when a checked checkbox is removed - the v-model still ...

Angular renders HTML elements

Greetings! I am currently experimenting with using AngularJS for the frontend and Wordpress as the backend of my project. To load content from Wordpress into Angular, I am utilizing a JSON wordpress plugin along with making $http requests. The content th ...

submitting image data from HTML5 canvas using an HTML post request

I am having issues sending canvas data to the server side as an image. Despite making an HTTP post request, I am unable to retrieve the data on the server side. $_POST remains empty, even though I can see the image data when console logging the object on t ...

What is the reason behind Vue.js duplicating its v-model data when the v-model is used within a computed property?

Consider the code snippet below: JavaScript const App = { template: '#app-template', data: () => ({ selected: [], items: Array.from({length: 50}, (x, i) => i+1).map(i => ({ id: i , name: `Item ${i}`, subtitl ...

Unfortunately, the server experienced a temporary error and was unable to fulfill your request at this time

When testing the Google Speech API for the first time, I followed the example provided in Google's demo and it was successful. { "config": { "encoding":"FLAC", "sample_rate": 16000, "language_code": "en-US" }, "audio": { ...

Chip input component in React

I've recently upgraded to React 17 and encountered an issue with chip input fields like material-ui-chip-input not working properly. I've tried various npm packages, but none of them seem to be compatible with React version 17. Does anyone know ...

The key to creating efficient routers in Express: Don't Repeat Yourself!

Currently, I am in the process of developing a web application in the form of a network structure that involves basic CRUD operations. However, I am facing the issue of having overly large router files, prompting me to consider splitting them up. One of t ...

Checking for palindromes in a 2D array

I am currently working on a task to determine if a 2D array is a palindrome both row-wise and column-wise using a String or Character variable. I am a bit confused as we are only covering 2D arrays and loops in our lesson, and I keep coming across referenc ...

Having trouble determining the dimensions of a newly added element

I am using jQuery to dynamically add an image but I am unable to retrieve its dimensions (width and height). Below is the snippet of code from my HTML file: <input type="checkbox" id="RocketElement" data-id="1"> And here is the JavaScript/jQuery c ...

What is the best way to activate an event using jQuery?

Currently, I am developing a web page where a modal window should open upon the user clicking on a specific radio button. To achieve this functionality through my jQuery code, I am trying to simulate the action of the user clicking on the radio button by: ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Using JLinq for Date-Based Filtering of JSON Data

I have been trying to use JLinq for filtering JSON data, but I am facing an issue with filtering by date. Despite attempting different methods, the problem persists. Below is a snippet of my code: //This works jlinq.from(myData) .select(function ...

FormData enables uploading of several images through distinct fields simultaneously

Looking to upload images to the server before submitting the form? Unable to nest forms, FormData() is being utilized. The form includes a title and 5 images with captions. The goal is to initiate the upload once an image is selected without clicking &apo ...

Unable to locate element in Internet Explorer when using frame switching within Selenium

I am currently working on a project in Selenium that is specifically designed to run in Internet Explorer, but I am encountering issues locating the xpath element. Despite this setback, I managed to make progress in the test by using the switch frame func ...

Steps to create a dynamic <div> that is only visible within a parent <div>

First of all, I want to express my gratitude for welcoming me into the group. I am seeking assistance with an inquiry regarding jQuery animation. The specific animation in question can be seen on the navigation menu items of this template from Template Mon ...

Receiving a 401 error while attempting to make an axios get request with authentication headers

I have been utilizing axios in my React project to fetch data from MongoDB. However, I am facing a challenge with the axios get requests returning a 401 error when I include my auth middleware as a parameter. This middleware mandates that the user must pos ...

What is the best way to sort through an array depending on a specific sequence of elements provided

I am trying to create a custom pipe in Angular 5 that filters an array of events based on a given sequence. For instance, if my data is: ["submit", "click", "go_back", "click",...] I want to filter this data based on up to three inputs. If input ...

What is the best method for retrieving high-resolution images from the Discogs API?

Is there a way to access higher quality images from the Discogs API? Currently, I am only able to retrieve thumbnail images of size 150x150. Is there a method for developers to obtain better resolution images? The JSON response contains links only for thum ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...