Arrange a JSON array by searching texts initially, followed by sorting the remaining results in alphabetical order

I am looking to sort a JSON array in JavaScript based on a search text. The sorting should prioritize items that match the search text at the beginning of their value, followed by alphabetical sorting for the remaining results. Even if the search text is found in the middle of an item's value, it should still be considered for sorting purposes.

Need solution in Javascript

Array :

[
{
 "value": "1",
 "text": "BEAUMONT Habitation 54"
},
{
 "value": "2",
 "text": "BEAUMONT Place de Renival"
},
{
 "value": "3",
 "text": "BEAUMONT Rue des Tiennes"
},
{
 "value": "4",
 "text": "BEAUMONT Rue Grand Chemin"
},
{
 "value": "5",
 "text": "BRUYERES Chênes"
},
{
 "value": "6",
 "text": "CEROUX Cabine"
},
{
 "value": "7",
 "text": "CEROUX Chapelle aux Sabots"
},
{
 "value": "8",
 "text": "CEROUX Place Communale"
},
{
 "value": "9",
 "text": "CEROUX Quatre Bras"
},
{
 "value": "10",
 "text": "Station Jambeaux"
},
{
 "value": "11",
 "text": "Reseau Street"
},
{
 "value": "12",
 "text": "beaux street"
}
]

EDIT

The current sorting method does not work as expected when the data is transformed into a different format. Some modifications were made to the code to try and make it work, but the issue persists.

   {
      "item":{
         "value":"1558",
         "text":"BEAUMONT Habitation 54"
      },
      "refIndex":0,
      "matches":[
         {
            "indices":[
               [
                  0,
                  1
               ]
            ],
            "value":"BEAUMONT Habitation 54",
            "key":"text"
         }
      ],
      "score":0.018533147937493524
   },
   {
      "item":{
         "value":"1560",
         "text":"BEAUMONT Place de Renival"
      },
      "refIndex":3,
      "matches":[
         {
            "indices":[
               [
                  0,
                  1
               ]
            ],
            "value":"BEAUMONT Place de Renival",
            "key":"text"
         }
      ],
      "score":0.03162277660168379
   }
]

A function has been implemented to handle the custom sorting logic:

function sortByInput(data, input = null) {
  if (!input) {
    return data.sort((a, b) => a.item.text.localeCompare(b.item.text));
  }
  
  return data.sort((a, b) => {
    const regex = new RegExp(`(^${input})`, "i");
    const aMatch = regex.test(a.item.text);
    const bMatch = regex.test(b.item.text);

    if (aMatch || bMatch) return -aMatch + bMatch;

    return a.item.text.localeCompare(b.item.text);
  });
}

Answer №1

To efficiently sort an array in JavaScript, you can utilize the default Array.sort method and provide a custom comparison function.


In the code snippet below, there is a condition to check for the presence of an input value. Based on this condition, the sorting operation may be purely alphabetical or involve sorting based on the input value (using regular expressions to identify matching elements).

const data = [
  { value: "1", text: "BEAUMONT Habitation 54" },
  { value: "2", text: "BEAUMONT Place de Renival" },
  { value: "3", text: "BEAUMONT Rue des Tiennes" },
  { value: "4", text: "BEAUMONT Rue Grand Chemin" },
  { value: "5", text: "BRUYERES Chênes" },
  { value: "6", text: "CEROUX Cabine" },
  { value: "7", text: "CEROUX Chapelle aux Sabots" },
  { value: "8", text: "CEROUX Place Communale" },
  { value: "9", text: "CEROUX Quatre Bras" },
  { value: "10", text: "Station Jambeaux" },
  { value: "11", text: "Reseau Street" },
  { value: "12", text: "beaux street" }
];

function sortByInput(data, input = null) {
  if (!input) {
    return data.sort((a, b) => a.text.localeCompare(b.text));
  }
  
  return data.sort((a, b) => {
    const regex = new RegExp(`(^${input})`, "i");
    const aMatch = regex.test(a.text);
    const bMatch = regex.test(b.text);

    if (aMatch || bMatch) return -aMatch + bMatch;

    return a.text.localeCompare(b.text);
  });
}

console.log(sortByInput([...data], "ceroux"));


Edit:

Here is an enhanced version featuring an additional parameter compareValue that specifies the property used for sorting (defaulted to "item.text" as per your example).

A new utility function getProp has been introduced to dynamically access properties of objects based on the specified compareValue.

function sortByInput(data, input = null, compareValue = "item.text") {
    const getProp = (object, path) =>
        path.split(".").reduce((o, p) => o[p], object);

    if (!input) {
        return data.sort((a, b) =>
            getProp(a, compareValue).localeCompare(getProp(b, compareValue))
        );
    }

    return data.sort((a, b) => {
        const regex = new RegExp(`(^${input})`, "i");
        const aMatch = regex.test(getProp(a, compareValue));
        const bMatch = regex.test(getProp(b, compareValue));

        if (aMatch || bMatch) return -aMatch + bMatch;

        return getProp(a, compareValue).localeCompare(getProp(b, compareValue));
    });
}

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

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

What is the best way to reload scripts each time a component is mounted?

My jQuery scripts include animation effects that need to be refreshed whenever something new is rendered on the page. However, I am facing an issue where the jQuery scripts are not being refreshed as needed. Below is my router configuration: export defau ...

Guide on updating specific sections of text within a MariaDB database column

I'm looking to update a specific portion of text in a MariaDB 10.5 database table with a new value. For example: Database: users Table: humans Column: area Values: as shown below row 1: ["area1","area2","area 3",& ...

Guide to Embedding Content Script into Local Page

Allow me to give you an overview of the current situation; I am in the process of developing a Chrome extension that conducts searches on specific websites, retrieves the results, and then opens a new tab containing a table where all the results are displ ...

Tips for adding animation to a React state value change triggered by an input

In my React application, I have a form with multiple fields that each contain a text input and a range input. Currently, both inputs share the same state value and onChange function to keep them synchronized. However, I would like to add an animation effe ...

Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side. https://i.stack.i ...

Is there an advantage to pre-compiling jade templates for production in an express environment?

Is it advantageous to have a middleware that pre-compiles all .jade views for production use, or does this happen automatically when NODE_ENV is set to 'production'? I am investigating ways to accelerate jade rendering for production purposes. ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

Converts csv logs into JSON format or any other method to obtain metrics

I am facing a challenge with analyzing a log file to extract statistics based on the captured logs. Here is a sample log format: 2023-03-09 18:55:56,INFO,capturing: DataIngestion 2023-03-09 18:55:57,INFO,waiting to get data 2023-03-09 18:56:58,INFO,time s ...

struggling to transfer information from JavaScript to Jade within the Node.js environment

Currently, I am retrieving a row from a Cassandra table called "emp". My objective is to pass the data retrieved from the JavaScript file to a Jade file in order to display this information on the user interface. In my JavaScript function: router.get(&a ...

Transitioning jQuery .load and the usage of sorttable.js for sorting data

My jQuery code snippet is as follows: $("#loadBtn").click(function(){ $('#div1').delay(200).slideUp('slow') .load ('page2.php #div2').hide().delay(300).slideDown('slow'); return false; ...

Accessing PHP variables in JavaScript

Hi there, I am new to all this. I am trying to figure out how to use a PHP variable in JavaScript. Here is a snippet of my code (popup.php): <?php $id_user = $this->session->userdata('id'); ?> <script type="text/javascript"> ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Error: The function "text.toLowerCase()" is not defined

Whenever I execute the following code, I keep encountering this error message: Uncaught TypeError: text.toLowerCase is not a function const getVisibleExpenses = (expenses, { text, sortBy, startDate, endDate }) => { return expenses.fi ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

How can I modify the text that appears when hovering over an element?

Can the displayed text be altered on mouse hover? For instance, can I change the text of a H1 tag when hovering over it using HTML, CSS, and JavaScript? ...

Optimal placement and size for the slick slider

I am new to CSS and currently experimenting with the Slick slider on a project: My setup involves a div container that spans 100% of the width of the page. Inside this container, there is another div (housing the slider) that takes up 80% of the width. D ...