Rearrange the elements of an array without altering the original

Looking for a way in JavaScript to sort an array without altering the element order but creating a "grouping" feature.

Example Data:

[
  {group: 'test',  title: 'A'},
  {group: 'test',  title: 'B'},
  {group: 'test2', title: 'C'},
  {group: 'test',  title: 'D'}
]

The goal is to use [].sort() to achieve this final order:

[
  {group: 'test',  title: 'A'},
  {group: 'test',  title: 'B'},
  {group: 'test',  title: 'D'},
  {group: 'test2', title: 'C'}
]

This means not changing the order of the first two items, only switching #3 and #4 based on their group. Using localeCompare would reorganize the groups alphabetically, which is not desired; their original order should be maintained.

UPDATE: To clarify further, I do not want to rearrange the group order alphabetically, they should remain in the same sequence as they appear.

Answer №1

It is essential to implement a custom comparison function when using Array.sort

let data = [
  {category: 'example', name: 'A'},
  {category: 'example', name: 'B'},
  {category: 'demo', name: 'C'},
  {category: 'example', name: 'D'}
];

function customComparison(a1, b1) {
    return a1.category < b1.category ? -1 : a1.category === b1.category ? 0 : 1;
}

data.sort(customComparison);

console.log(data);

Answer №2

Give this a shot:

function sortTitles(bookA, bookB) {
  if (bookA.title < bookB.title)
     return -1;
  if (bookA.title > bookB.title)
    return 1;
  return 0;
}

books.sort(sortTitles);

Answer №3

To tackle this sorting challenge, you can implement a comparison function like the following:

function customSort(a, b) {
  if (a.category == b.category) {
    return a.name < b.name ? -1 : a.name == b.name ? 0 : 1;
  }
  return a.category < b.category ? -1 : 1;
}

yourArray.sort(customSort)

If I correctly interpreted your query, you aim to first sort by categories and then by name within the same category.

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

Tips for transferring parameters to functions within middleware

Attempting to pass a parameter to a middleware has presented some challenges for me. Within the routes' handler, I have the following function: router.get('/users', auth.required, userController.findAll); This function then leads to the a ...

I encountered a Node.js 203 error specifically on my computer - could this be linked to a specific environment and is there a way to resolve it

Let me explain what happened: I was working on a Nodejs-express-angular example by Brian Ford the other day, and everything was running smoothly. update:----------------this part of problem has been solved---------- However, after a few hours (during wh ...

RegEx - Finding exact matches without any additional characters trailing

I am currently trying to find matches in the given strings: 'Los Angeles, CA' 'New York, NY' 'Williamsburg, Brooklyn, NY' by comparing them with the following input strings: 'Los Angeles, CA 90001, USA' 'New ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...

The NEXT_LOCALE cookie seems to be getting overlooked. Is there a mistake on my end?

I am looking to manually set the user's locale and access it in getStaticProps for a multilingual static site. I have 2 queries: Can a multilingual website be created without including language in the subpath or domain? Why is Next misinterpreting m ...

Ways to troubleshoot setTimeout functioning during HTTP requests?

Utilizing Socket IO in my client app, I have implemented a feature to check for unread events. The process involves making a request to the backend, which then sets a 5-second timeout before checking for any new events and sending them back. // client soc ...

Mobile browser experiences video freezing when src is set through useState, yet it starts playing when triggered by a button click or when the video is set to M

Hey awesome folks at the StackOverflow Community, I'm currently encountering a perplexing issue with a video element in my web application. The video is supposed to play automatically on both desktop and mobile browsers. However, I've run into a ...

What is the best way to highlight excess characters in Kendo UI Editor by setting the selectedRange, similar to Twitter's feature

Can anyone provide guidance on wrapping parts of the nodes in a Kendo UI Editor with a span when they exceed the character limit? I'm looking to replicate the feature in Twitter where excess characters are shown in red. Is there a way to adjust the s ...

Emphasize the present selection along with all prior items in a menu

Attached is my menubar for a unique web design concept I am working on. My webpage is designed as a fully scrollbar page shift type, meaning it is a single page containing six sections that are scrollable by selecting menu items. Currently, when I click ...

Debugging and profiling JavaScript directly in the web browser

I am searching for a solution that allows me to observe which JavaScript functions are being called in the browser while I browse a website. I envision something similar to Firebug (which might actually be capable of this, but I have not discovered how ye ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Storing Data in Web Browsers: HTML5's localStorage, Cookies, and

After browsing through numerous search results on SO, it seems that HTML5's localStorage feature is particularly advantageous compared to Cookies for storing large amounts of data that doesn't need to be sent to the server. (Local Storage vs Cook ...

Flawless 2D mouse selection using Canvas for pixel-perfect accuracy

Currently, I am developing a 2D game in HTML5 using Canvas that requires precise detection of mouse click and hover events. The main challenges I am facing include the need for pixel-perfect detections, working with non-rectangular objects such as houses a ...

Using the <video /> tag on a Next.JS page generated on the server side leads to hydration issues

My Next.js app's index page is rendered on the server side by default. During development, I encountered an error that stated: Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server. Wa ...

Steps for generating tab panels and their respective content using a v-for loop

I am currently utilizing Vue 3 in combination with Bootstrap 5. My objective is to incorporate multiple Tabpanels within a v-for. Each of these Tabs should feature distinct content. To achieve this, I attempted placing my Tabs and their respective Conten ...

What is the best way to assign a class to certain columns within a table?

I'm working on a code that generates random numbers for 3 columns and checks if each generated number exceeds +5/-5 of its previous number. However, I've encountered an issue where the first two columns always have the "blink" CSS applied to them ...

Choose an element from within a variable that holds HTML code

I have a specific div element that I need to select and transfer to a new HTML file in order to convert it into a PDF. The issue I'm facing is related to using AJAX in my code, which includes various tabs as part of a management system. Just to prov ...

What is the best way to retrieve a file using XMLHTTPRequest and Ajax?

I am currently using window.location.href to download a file, but this method requires a second call to my servlet which takes about 1 minute to generate the file. How can I download the file using XMLHTTPRequest instead? The solution should only work wi ...

Efficiently sanitizing a JavaScript object using the replace() method in JavaScript

I have a data object structured like this {"paymethod_id":1,"business_id":76,"delivery_type":"1","driver_tip":0,"delivery_zone_id":6569,"delivery_datetime":null,"location":{&qu ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...