Is there a way to use the sort() function to further categorize objects that have been moved to the bottom of an array during sorting?

My task in JavaScript involves sorting within a single sort() function that is passed as a parameter.

Specifically, I need to sort objects first by category and then further sort them by subcategory using:

return item1.category.localeCompare(item2.category) : item1.subCategory.localeCompare(item2.subCategory)

However, for objects without a category, I want to place them at the bottom of the list. The current approach I'm using does this but the items are not grouped together by subcategory as desired.

Here's an example of how the sorted objects look now:

[
  {'category':'cat1', 'subcategory':'subcat1'},
  {'category':'cat1', 'subcategory':'subcat2'},
  {'category':'cat2', 'subcategory':'subcat1'},
  {'category':'cat2', 'subcategory':'subcat2'}
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'},
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'}
]

I would like the final result to be organized by subcategory with empty categories staying grouped together. For instance:

[
  {'category':'cat1', 'subcategory':'subcat1'},
  {'category':'cat1', 'subcategory':'subcat2'},
  {'category':'cat2', 'subcategory':'subcat1'},
  {'category':'cat2', 'subcategory':'subcat2'}
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat1'},
  {'category':'', 'subcategory':'subcat2'},
  {'category':'', 'subcategory':'subcat2'}
]

Answer №1

To begin, prioritize sorting the empty parts to the bottom before comparing the strings within the category and subcategory.

var data = [{ category: 'cat2', subcategory: 'subcat1' }, { category: 'cat1', subcategory: 'subcat1' }, { category: 'cat2', subcategory: 'subcat2' }, { category: '', subcategory: '' }, { category: '', subcategory: 'subcat1' }, { category: '', subcategory: 'subcat2' }, { category: 'cat1', subcategory: 'subcat2' }, { category: 'cat1', subcategory: '' }, { category: 'cat2', subcategory: '' }];

data.sort(function (a, b) {
    return (
        !a.category - !b.category ||                 // place falsy values at the end
        a.category.localeCompare(b.category) ||      // arrange strings alphabetically
        !a.subcategory - !b.subcategory || 
        a.subcategory.localeCompare(b.subcategory) 
    );
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you want to dynamically sort objects based on multiple properties, you can achieve this by utilizing a helper function and nested sorting logic for as many fields as needed.

function getGeneratedObjects(num){  // helper function to generate sample objects
  return Array(num).fill()
                 .reduce(obj => obj.concat({prop1 : String.fromCharCode(...Array(5).fill().map(_ => ~~(Math.random()*26)+97)),
                                        prop2 : ~~(Math.random()*5)+1,
                                        prop3 : ["London","Paris","Sydney","Berlin","Tokyo","Cairo"][~~(Math.random()*6)],
                                        prop4 : ~~(Math.random()*2+1)+String.fromCharCode(~~(Math.random()*3)+65)
                                       }),[]);
}

function multiLevelSorter(objects,props){
  return objects.sort(function(a,b){
                   var prop = props.find(f => a[f] !== b[f]);
                   return a[prop] < b[prop] ? -1 : 1;
                 });
}

var samples = getGeneratedObjects(50),
sortOrder = ["prop3","prop2","prop4","prop1"],
   sortedData = multiLevelSorter(samples,sortOrder);
sortedData.forEach(item => console.log("{prop1:", item.prop1,"prop2:",item.prop2,"prop3:",item.prop3,"prop4:",item.prop4,"}"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Therefore, the script above arranges data in the order of priority defined as prop3 -> prop2 -> prop4 -> prop1.

Answer №3

If you prefer, you can utilize the SortedArrayCategory. Here is how the code looks:

//arrTemp = The name of your array.

                                self.sortedArrayCategory = arrTemp.sortedArrayUsingComparator {
                                    (firstObject, secondObject) -> NSComparisonResult in

                                    let item1 = firstObject as! String
                                    let item2 = secondObject as! String
                                    let comparisonResult = item1.compare(item2)
                                    return comparisonResult
                                }

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

Guide to creating a new Fabric.js canvas

I'm running a platform where users have the ability to manipulate images within a Fabric.js canvas. My goal is to replicate their "design" on a larger canvas, so I'm wondering what methods exist for recreating a canvas using the original variable ...

What is the process for validating a JWT token using an x.509 certificate in a Node.js environment?

I need assistance with making a node script capable of validating a JWT token. I possess the public key, which is an x.509 certificate, along with the JWT itself. My attempt to utilize https://github.com/auth0/node-jsonwebtoken proved unsuccessful as it d ...

A problem arises when utilizing jQuery's $.isArray functionality

Successfully executing an AJAX post, the function test is utilized to process the passed data. $("#formID").submit(function (event) { $('#postError').html('').hide(); $('#postInfo').html('loading results').s ...

Even when only a handful of modules are utilized, Webpack still imports a significantly large existing chunk

Currently, I am working on enhancing the splitChunks configuration in a multi-page application that utilizes Webpack 5, with a PHP backend and a Vue frontend. To optimize the vendor file size, I have started customizing the test function of the vendor cac ...

There is an issue with XMLHttpRequest loading http://*********. The requested resource does not have the necessary 'Access-Control-Allow-Origin' header

Just getting started with node, javascript, and other related technologies. I encountered an Access-control-allow-origin error while attempting to execute a GET request using XMLHttpRequest. Despite searching extensively for a solution, nothing seems to be ...

By utilizing the window.history.back() function, it takes me four clicks to navigate back one page

I find it peculiar that my back button is using the JS method window.history.back() to return to the previous page. However, I have noticed a strange behavior with this button. When I click on it before the entire document loads, it functions as expected a ...

Julia's Guide to Efficiently Mutating Type-Stable Arrays

Hello everyone! I am new to Julia and I hope you don't mind if my question seems basic. I have been working on a scientific program where I am dealing with multiple arrays that are type-stable and have a fixed dimensionality. These arrays are updated ...

How can I extract an array from a string using JSON parsing?

Currently, I am initiating a GET request through HTTP to a specific file in php that responds with a JSON encoded array. The returned Array is structured as a 2x2 Array. My goal is to handle the output of the HTTP request and construct a similar 2x2 Array ...

The function onNotificationGCM in Cordova PushNotification is not triggered

I am currently working on implementing push notifications for both Android and iOS. For this task, I have utilized a cordova push-plugin from the following link: https://github.com/phonegap-build/PushPlugin, and so far, it has been functioning excellently ...

Pass an array using AJAX to my Python function within a Django framework

I am attempting to pass an array to my python function within views.py, but I am encountering issues. It consistently crashes with a keyError because it does not recognize the data from js. Code: Python function in views.py: def cargar_datos_csv(request ...

What are the best practices for formatting a .js file using JavaScript and jQuery?

I've recently started incorporating JavaScript and jQuery into my website, but I'm encountering issues with formatting the code. Each section of code works fine independently, but when I combine them into a single .js document, the slideshow part ...

React Crop by FilePond

I am currently working on integrating the plugins for the Filepond library into a React.js project with Firebase as the backend. Unfortunately, I am facing some challenges with implementing the cropping plugin. My goal is to enforce a 1:1 crop ratio on all ...

Using a Button component as a TableCell in a material-ui Table

Hey there! I'm looking for some assistance in adding buttons as TableRowColumns in the material-ui Table. I'm working on implementing an approval system to approve or reject user requests, and I thought presenting them in a tabular format would b ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Problems with Ajax functionality in CodePen

Currently working on the Wikipedia Viewer project for freeCodeCamp. I'm encountering an issue with the ajax function as nothing is being logged in the console upon click. The code snippet in question is provided below. Appreciate any help or insight o ...

What is the best way to establish a connection with MSSQL using Node.js within a Vue.js frontend environment

Seeking assistance with connecting Vue.js app to remote MSSQL server. Incorporating node.js and utilizing the mssql library, encountering errors post-setup. How can I configure settings for successful mssql connection? What are effective solutions for r ...

Activating event with mouse click or keyboard shortcut

I have a function that displays a form dialog with JqGrid when a link is clicked. This is how my code looks: HTML: <div id="mainDialog"> <a href='#' class='showList'>Show list [Ctrl+L]</a> .... </div& ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...

Plotting data with both line and nested plot in d3

My plot graph has the correct color scheme, but I need to connect each plot with lines. There are two groups of plots that need to be nested into separate line groups. I'm unsure how to proceed with this task. <!DOCTYPE html> <html> < ...