Arrange items in a custom order in Javascript by grouping specific items at the bottom and sorting the rest

My JavaScript challenge involves an array of items like this:

[
  'title',
  'firstname',
  'company',
  '[m]usr_phone'
  '[m]usr_city'
]

I am looking to implement a custom array sort function that will arrange all non-[m] items at the beginning, followed by [m] items at the end.

I attempted to create a sort function as follows:

function(a, b) {
            if (!a.indexOf('[m]') && b.indexOf('[m]') === 0
                || a.indexOf('[m]') && b.indexOf('[m]')) {
                    return -1;
            }

            if (a.indexOf('[m]') === 0 && !b.indexOf('[m]')) {
                return 1;
            }

            return 0;
        }

However, I faced issues making it work correctly. The desired output should be:

[
  'company',
  'firstname',
  'title',
  '[m]usr_city'
  '[m]usr_phone'
]

Your assistance on this matter is greatly appreciated!

Answer №1

To organize the array based on prefixes, consider using the String#localeCompare method for sorting.

var array = ['name', 'age', 'city', '[p]phone', '[a]address'];

array.sort(function (x, y) {
    return (x.slice(0, 3) === '[a]') - (y.slice(0, 3) === '[a]') || x.localeCompare(y);
});

console.log(array);

Answer №2

To ensure consistency when comparing items in the same "class" (defined as starting with [m] or not), use

a.startsWith("[m]") == b.startsWith("[m]")
for comparison, and then employ String#localeCompare.

console.log([
  "name",
  "age",
  "gender",
  "[m]usr_email",
  "[m]usr_address"
].sort((a, b) => {
  if (a.startsWith("[m]") == b.startsWith("[m]")) {
    return a.localeCompare(b);
  } else {
    return (a.startsWith("[m]") ?
      1 :
      -1);
  }
}));

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

Do not include objects in the search results that lack necessary information

My ng-repeat code looks like this: <div layout="row" flex layout-wrap layout-margin layout-padding> <tile ng-repeat="camp in ctrl.camps | filter:{ctrl.search} track by $index"></tile> </div> The ctrl.camps object array is str ...

Uploading files using AJAX without the use of libraries

I am attempting to create a lightweight file upload feature. While there are many solutions using jQuery for file uploads on SO, I would prefer not to use it. I am exploring ways to validate and upload a file to the server using plain Javascript (without ...

The table refuses to load

I've been troubleshooting this issue for the past two days. The array is visible in the console, but it refuses to show up on the table. I've tried multiple approaches, but none seem to work. I suspect that "tobodyHtml" is not defined properly, a ...

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

Creating an external JavaScript and CSS file for date picker in Eclipse can be done by following a few simple steps. By creating separate files for the

I am using the following javascript and css styles: <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jq ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

Ways to identify if there is a problem with the Firestore connection

Can anyone help me understand how I can use angularfire2 to check the accessibility of the cloud firestore database and retrieve collection values? If accessing the cloud database fails, I want to be able to retrieve local data instead. This is an exampl ...

What is the process for generating a new object by outputting key-value pairs?

I have an array that I'm trying to use to create a new object with specific keys and values. const arr = [ { name: 'ab', key: '584577', }, { name: 'cd', key: '344926', }, { name: &a ...

AngularJS triggers the function on all controllers

I encountered a problem with a specific function in my code. The issue is that the scrollFunction continues to get triggered even when I navigate to another page. I would like to limit this functionality to only apply to a particular page within the cont ...

JavaScript placeholder-type expression

Hey there, I am a C++ developer who is venturing into the world of JavaScript. While exploring JavaScript syntax, I stumbled upon something that resembles templates in C++. For example, while going through RxJs tutorials, I came across this line of code: ...

Struggling to understand the relationship between SetInterval and closures

Is there a way to continuously update the contents of a div using setInterval I found inspiration from this question on Stack Overflow: How to repeatedly update the contents of a <div> by only using JavaScript? However, I have a couple of questions ...

Scriptmanager and Rokbox clash in a heated confrontation

I'm having trouble getting RokBox to display images on my webpage because the asp:ScriptManager seems to be causing some issues. After trying to troubleshoot, I found that when I remove the following code: <asp:ScriptManager ID="ScriptManager1" r ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

What are the methods to ascertain whether an HTML element possesses a pseudo element?

Is there a method to identify whether an HTML element has a pseudo element (::before / ::after) applied to it without invoking the function: window.getComputedStyle(element, ":before/:after"); MODIFIED: the response is NEGATIVE The issue with getCompute ...

Creating a JSON file using an object to send requests in Angular

In my Angular 7 project, I am trying to send a multipart request to the server that includes a file (document_example.pdf) and a json file containing a data object (data_object_example.json). The content of data_object_example.json is as follows: { " ...

Instantly appearing and disappearing Bootstrap modal popup catches users off guard

I've encountered an issue with my bootstrap popup that displays student results - it opens and closes immediately. In my master page file, I have included the following JS files: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="ser ...

Utilizing JavaScript variable modifiers for enhanced functionality

I'm trying to find a way to perform a case-insensitive search for a variable within a string. To achieve this, I'm using the /gi modifier to ignore case sensitivity. However, the challenge arises because identifiers only accept direct strings rat ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Tips for utilizing the @run-at document-start meta-rule

Currently, I am utilizing the following code snippet: Jquery(window).load(function(){ // here is my code for making an AJAX request to retrieve data from the database }); Unfortunately, I have encountered an issue specifically with its function ...

When attempting to add a respond_to in ActionController, an ActionController::UnknownFormat error

After removing respond_to and render to view, everything seems to be working smoothly, but when I include the js render, I encounter an error. controller code : if params[:stock].present? @data = params[:stock] @stock = Stock.new_form_lookup(params[ ...