How to arrange different components of an array in JavaScript

Seeking a proficient approach to the issue at hand:

https://i.sstatic.net/JP8aE.png

In essence, the goal is to prioritize items with a pending status at the top and arrange all other statuses below, then sort each section alphabetically by name.

Here is my current solution implementation:

arrangeData(data){
  const pending = [];
  const nonPending = [];
  data.forEach((item) => {
     if(item.status === 'Pending') { //case insensitive logic can be incorporated
        pending.push(item)
     } else {
        nonPending.push(item);
     }
  });

  pending.sort((a, b) => {
    return a.name.localeCompare(b.name);
  });

  nonPending.sort((a, b) => {
    return a.name.localeCompare(b.name);
  });

  return pending.concat(nonPending);
}

Answer №1

Make sure to check the status before sorting for efficiency.

const items = [
  { id: 1, name: "X", role: "User", status: "" },
  { id: 2, name: "Z", role: "Admin", status: "" },
  { id: 3, name: "Y", role: "Supervisor", status: "Pending" },
  { id: 4, name: "W", role: "", status: "" },
]

const sortedItems = sort(items);

sortedItems.map(item => console.log(JSON.stringify(item)));

function sort(data) {
  return data.sort((a, b) => {
    // Move pending items to the top
    if (a.status === 'Pending' && b.status !== 'Pending') return -1;
    // Push non-pending items down
    if (a.status !== 'Pending' && b.status === 'Pending') return 1;
    
    // Sort by name 
    return a.name.localeCompare(b.name);
  });
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Note: To handle non-unique names, consider adding sorting rules for ID or role as well.

return a.name.localeCompare(b.name) || // Sort by name first
       a.role.localeCompare(b.role) || // Next, compare roles
       a.id - b.id;                    // Lastly, sort by ID

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

Javascript inheritance concepts

Creating a set of classes in JavaScript to manage accounts presents a challenge for me. The main class is 'account', which serves as the parent class, while 'depositAccount' and 'savingsAccount' are its children. These classes ...

Ways to return to a previously active div when clicking the back link on a webpage

My approach involves toggling between different divs when clicking on links. Each div contains its own form which submits data to a new page, and then I use a "go back" link to return to the previous page. However, the issue arises when the active div at ...

The manipulation of Analytics with artificial pageviews is altering the source of traffic for PPC campaigns

Currently, we are facing some challenges with a website called . It appears that only the PPC traffic source is affected by changes caused by the pageviews being pushed through to analytics. Since the website operates on Ajax, we need to utilize Javascrip ...

How to efficiently manage drop-down menus on a website using VBA specifically designed for Internet Explorer

I am a beginner in VBA and coding, seeking assistance from the community. The purpose of this VBA code is to automate the following steps: Open Internet Explorer Enter user ID and password to login Select the current date Select a specific option (X1) fr ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

The remove() function is failing when attempting to add input fields dynamically

Hello, I am currently facing an issue with dynamically generating input fields based on AJAX results. Unfortunately, the .remove() function is not working as expected and my current solution involves repetitive code. Any guidance or assistance would be g ...

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...

Use Javascript to dynamically load a PHP file with the include function

I've been searching for a solution to this issue with no luck so far. Spending hours trying to figure it out. On my PHP page, I'm making an SQL call and dynamically building the content. There's a list of items with onClick JavaScript funct ...

Preventing duplicate submissions ensures that submissions are sent only once

Encountered an issue with the multiple form page I'm working on: There are two forms present: <form> <input type="submit" id="single-submit" name="form_1" value="Submit 1"/> </form> <form> <input type="submit" id="single- ...

Using dates as the X axis in Chart.js can be achieved even when there is no corresponding Y axis value

My goal is to ensure that the chart always displays a value on the final X axis, I am unable to use "distribution: 'series'" as it causes the chart to go out of scale, Guessing the correct value to set for "time: {min / max}" in order to exceed ...

To dismiss a popup on a map, simply click on any area outside the map

Whenever I interact with a map similar to Google Maps by clicking on various points, a dynamically generated popup appears. However, I am facing an issue where I want to close this popup when clicking outside the map area. Currently, the code I have writte ...

Ways to retrieve a value within a function and update a variable

Fetching data from the firebase database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ console.log('Error!'); console.log(err); } function gotData(d ...

Create a modal dialog in CSS that dynamically adjusts its size without extending beyond the edges of the screen

I'm in the midst of developing a web application specifically for tablets. My goal is to display a modal dialog with a title bar and body that dynamically adjusts in height based on its content. If the content exceeds the viewport size, I want the dia ...

How to incorporate paginating in MongoDB operations

It's a well-known fact that using skip for pagination can lead to performance issues, especially as the data set grows larger. One workaround is to leverage natural ordering using the _id field: //Page 1 db.users.find().limit(pageSize); //Get the id ...

JQuery ID Media Queries: Enhancing responsive design with targeted

Is it possible to integrate a media query into the selection of an ID using JQuery? For example: $('#idname') $('@media (max-width: 767px) { #idname }') In essence, can you target the #idname with that specified media query in JQuery ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Ways to reduce the quality of an image before uploading it to Firebase

Having recently created a chat app with reactJs and firebase, I encountered an issue when trying to upload images with larger file sizes in MB. The images would successfully upload if they were only a few KB, but I needed a way to reduce the size of thes ...

What is the method for transforming negative byte values into megabytes, gigabytes, and beyond?

One challenge I am facing in my Angular application is converting bytes to units such as MB, GB, etc. The data I need for conversion is coming from the backend. For instance, I have data on All RAM, Available RAM, and Used RAM. These values are stored as ...

A guide to accessing items imported from a glb file within the Babylon JS game engine

When I use the BABYLON.SceneLoader.ImportMesh() method to load a .glb file created in Blender, one of the objects is named Cube.003. Surprisingly, after calling the method, Cube.003 is not included in the scene.meshes array. It does show up in the scene ...

Is the password encryption method secure enough?

Embarking on my first project in Node.js with technologies like MongoDB, Mongoose, and Express, I found myself deep into the world of cryptography while tackling user authentication. Encryption other than this isn't necessary for this particular proje ...