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

Retrieve the chosen selection from a dropdown menu using AngularJS and Ionic

I've been encountering some issues with the select feature in AngularJS. Despite searching extensively for solutions, none seem to be working for me. The JSON structure I'm dealing with is generated from my service.php: [ { "Name": ...

Duo and reference loop

I'm trying to learn how to use backreferences in JavaScript. I have an array and want to replace it within a string. Here's what I've attempted so far: var items = ["book", "table"]; var sentence = "The $1 is on the $2"; var newSentence ...

Ways to arrange an array in JavaScript or jQuery when each array record contains multiple objects

Before giving a negative vote, please note that I have thoroughly searched for solutions to this problem and found none similar to what I am facing. I am looking to alphabetically sort the array by image.name using JavaScript or jQuery: var myArray = [{ ...

Transition from mouse wheel scroll to page scroll not functioning properly when overflow is enabled

The website has a fixed element that uses overflow:auto. Users can scroll this element by positioning the mouse over it. However, once the element reaches the end of its scroll, the page does not seamlessly take over the scrolling. Instead, there is about ...

Error: Unexpected end of input detected (Likely due to a missing closing brace)

I've been struggling with this bug for the past two days, and it's driving me crazy. I have a feeling that I missed a brace somewhere in my script, but despite running various tests, I can't seem to pinpoint the glitch. Hopefully, your eyes ...

Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller? In case my model is structured like this: public class Donation { public string DonorType { get; set; } //etc } But the f ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

Automatic Expansion Feature for HTML Tables

http://jsfiddle.net/bzL7p87k/ In my table, placeholders are filled with special words. However, what happens when I have more than 4 rows? For instance, if there are 21 placeholders for 21 rows? What I mean is this: I only have one row with a placeholder ...

Pass a PHP array to JavaScript and use jqplot to create a plot

I am currently using jqplot to plot data that originates from a PHP array. However, I have encountered an issue when trying to plot the data using JavaScript. Here is the PHP code: $array= array(); $array[] = 34.890; $array[] = 25.090; And here is the c ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

Guide on how to navigate back to the login page when the access_token in local storage is not defined

Whenever my localStorage turns undefined, I need to redirect the user to the login page. However, this is not working as expected and I'm not sure what the issue is. Below is the code from my PrivateRoute.js: PrivateRoute.js import React from " ...

Necessary within a JavaScript Class

As a newcomer to using classes in JavaScript, I've been exploring the best practices and wondering about how 'requires' work when used within a class. For example, let's say I want to craft an IoT Connection class for connecting to the ...

When using JavaScript to redirect with window.location, the referrer header is not properly set

Currently, I am attempting to utilize window.location in React to redirect to a third-party page. However, upon making the redirect, the third-party server is not receiving a referrer header from my redirection. Any assistance on resolving this issue wou ...

Difficulty arising from implementing v-if as a filter within a v-for loop in Vue.js

I'm struggling a bit with setting up a conditional statement using v-if along with a loop using v-for in Vue. Here's what I have so far: <div class="row form-group" v-for="(article, key, index) in articles" :key="key" v-if="article.pubdate(fi ...

What is the process for compiled node projects to manage modifications to internal files?

I am currently developing a small program using nodejs that I intend to integrate as a backend service for an expressJS webserver that is still in the works. To prevent displaying the entire program on the webserver itself, I have learned about the possib ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

Mastering Play and JSON Transformations: Strategies for managing optional input and overcoming potential failures

Here is a find method designed to retrieve documents that meet specified criteria and optionally sort them based on the provided parameter sort: class DaoComponent { ... val toObjectId = (__.json.update((__ \ '_id \ '$oid).json.c ...

Guide on extracting data from a specific column in an object and converting it into a list using JavaScript

Imagine we are working with the following JSON information var example = [{ latitude: 11.1111, longitude: 111.111, name: "for example1", altitude: 88 }, { latitude: 22.2222, longitude: 222.222, name: "for example2 ...

Generate your own unique referral links today

Searching for ways to generate and monitor referral links like www.domain.com/?ref=switz What steps should I take to accomplish this? ...