Sorting an array based on the presence of a specific character in JavaScript: [JS]

I have an array named files:

['Cpp-New.html', 'dirname', 'dirname.html', 'dirname.py', 'HarryPotter', 'Java-New.html', 'poop.css', 'test01.html', 'Web-New.html']

that is being displayed in html. (List)

However, I want to sort it in a way that all elements without a file extension appear at the top. Currently, the browser displays the array in alphabetical order.

How can I achieve this? I tried researching but could not find a solution.

Thank you.

Answer №1

const items = ['index.html', 'style.css', 'app.js', 'image.jpg', 'data.json'];

const extRegex = /\.[a-z0-9]{1,4}$/;
const sortedItems = items.sort((x, y) => {
  const xHasExt = extRegex.test(x);
  const yHasExt = extRegex.test(y);
  return xHasExt - yHasExt;
});

console.log(sortedItems);

Answer №2

To implement this concept, I utilize a scoring system. For instance, if a period is present in the item, I prepend a 1. If not, I prepend a 0. This makes sure that items without a period are ranked higher in the sorting order.

For example:

const arr = ['Cpp-New.html', 'dirname', 'dirname.html', 'dirname.py', 'HarryPotter', 'Java-New.html', 'poop.css', 'test01.html', 'Web-New.html'];

const score = a => `${a.includes('.')?'1':'0'}${a}`

arr.sort((a,b) => {
  return score(a).localeCompare(
    score(b), undefined, {sensitivity: 'base'});
});


console.log(arr);

Answer №3

// This code provides a solution without the use of JavaScript sorting techniques.

const values = ['Cpp-New.html', 'dirname', 'dirname.html', 'dirname.py', 'HarryPotter', 'Java-New.html', 'poop.css', 'test01.html', 'Web-New.html'];
let j = 1;
let i = 0;
while(i < values.length) {
    
    if(j >= values.length) break;
    if(values[i].includes(".")) {
        i++;
        j++;
        continue;
    }
    
    if(!values[i].includes(".") && values[j].includes(".")) {
        // swap
        let temp = values[i];
        values[i] = values[j];
        values[j] = temp;
        continue;
    }
    
    if(!values[i].includes(".") && !values[j].includes(".")) {
        j++;
        continue;
    }
};

console.log(values);

Answer №4

this is concise, even though it disrupts the alphabetical order

const arr = ['Cpp-New.html', 'dirname', 'dirname.html', 'dirname.py', 'HarryPotter', 'Java-New.html', 'poop.css', 'test01.html', 'Web-New.html'];

arr.sort((a) => a.includes(".") ? 1 : -1 );

console.log(arr);

It's important to note that the sort operation alters the array, an alternative approach without using sort could be:

const newArr = arr.filter(a => !a.includes(".")).concat(arr.filter(a => a.includes(".")))

Answer №5

This method is effective even with an unsorted list, as it only requires sorting once:

names = ['Cpp-New.html', 'dirname', 'dirname.html', 'dirname.py', 'HarryPotter', 'Java-New.html', 'poop.css', 'test01.html', 'Web-New.html']
re = /.*\..+$/ 
names.sort((a, b) => re.test(a)-re.test(b) || a.localeCompare(b)) 

Here's how it works:

  • re.test(a)-re.test(b) returns 0 (false) when both items a and b either have or don't have an extension, proceeding to the expression after ||. Otherwise, it determines the sorting based on the extension.
  • a.localeCompare(b) compares a and b alphabetically, while disregarding case and accents.

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

Tables that respond to changes in screen size, allowing nested table cells to inherit widths

I am currently working on a responsive table with unique content in each row and a concertina feature for expanding rows. When the concertina is activated, it adds another row to the table below the current row, using a td element with a colspan attribute ...

Sending numerous arguments to getStaticPaths() in nextjs

I am looking to create two different routes: /midterm/cs611 /finalterm/cs611 My goal is to display distinct content when accessing the /midterm/cs611 endpoint, and different content when accessing the /finalterm/cs611 endpoint. However, I am running into ...

Error in Mongodb: Unable to convert value into ObjectId

Currently, I am attempting to retrieve only the posts belonging to users using the following code snippet: router.get("/:username", async (req, res) => { try { const user = await User.findOne({ username: req.params.username }); const ...

Unable to activate the date range picker

I am having trouble with integrating the daterange picker on my webpage. I can't seem to get it to work properly. Can anyone help me figure out what I might be doing wrong or if there's something missing? CSHTML: <div class="has-feedback" &g ...

Issue with nodes/JavaScript: Array objects not being properly updated

Being new to Javascript and Node.js, I attempted to code a simple program that generates an array of planes with varying index values. I started by defining a plane object with default values and tried to update the index value in a for loop. However, whe ...

Using jq to arrange JSON objects by their date values

Is there a way to arrange the json output based on the "lastModified" value? I have attempted various approaches using jq but have not been successful. The provided example is just one of several entries. I tried running jq -s '.[].items |= sort_by(. ...

Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows... .menu_closed { color: red; } .menu_open { color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Ways to address memory leakage issues in Angular

Is there a way to manually optimize the Garbage Collector by forcefully pushing variables into it? For example, if we have a root or global level variable in an Angular component that is no longer needed when switching to another page, how can we ensure it ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

What is the reason behind the absence of the C++ syntax for a string loop in javascript?

UPDATE: At first, I believed that the following syntax was not functioning due to a mistake in my code and the fact that I have not encountered it being utilized in Javascript before. My primary concern lies in why this particular syntax is not more preval ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...

Granting permission to the user

I am facing an issue with authorizing the admin user. Although the backend code is functioning properly, I am encountering difficulties in requesting the admin route and authenticating the logged-in user. Initial attempts involved storing the isAdmin value ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...

Is it possible in Typescript to assign a type to a variable using a constant declaration?

My desired outcome (This does not conform to TS rules) : const type1 = "number"; let myVariable1 : typeof<type1> = 12; let type2 = "string" as const; let myVariable2 : typeof<type2> = "foo"; Is it possible to impl ...

What is causing the issue with using transition(myComponent) in this React 18 application?

Recently, I have been immersed in developing a Single Page Application using the latest version of React 18 and integrating it with The Movie Database (TMDB) API. My current focus is on enhancing user experience by incorporating smooth transitions between ...

Why does replacing <input> with <TextField> in Material-UI & React cause the form submission to fail?

Recently, I encountered an issue with my CRUD Todo app's form for adding tasks. Initially built with a basic HTML input and button setup, I decided to enhance the design using Material-UI components. After introducing <TextField> in place of th ...

JSdom, automation, web scraping, handling dynamic iframes

I am currently in the process of automating my tasks on the website provided at the link below: I need to fill out forms and submit them automatically. So far, I have been successful in automating using Greasemonkey and I am now considering switching to ...