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);
});
}