Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort only strings from an array that meets the criteria

I need your help with this problem:
For example I have an array something like:

[
'3040-200021'
'4502-Frac 01'
'4504-Frac 16-J-10370'
'4504-Frac 16-J-10224'
...
...
...
]

I want to sort only the strings that has the same sintax as the last two strings and then get something like this:

[
'3040-200021'
'4502-Frac 01'
'4504-Frac 16-J-10224'
'4504-Frac 16-J-10370'
...
...
...
]

If I do myArray.sort() works but it reorders all the array and I only want to reorder the strings that has 3 dashes as the example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I do myArray.sort() works but it reorders all the array and I only want to reorder the strings that has 3 dashes as the example

>Solution :

You can use the sort function in combination with a custom comparison function to sort only the elements in the array that have the desired syntax. Here is an example of how you could do this:

myArray.sort(function(a, b) {
 // Check if both elements have 3 dashes
 if (a.split("-").length === 3 && b.split("-").length === 3) {
   // Sort the elements based on the third part of the string
   return a.split("-")[2] > b.split("-")[2];
 } else {
  // Leave the elements in their original order if they do not have 3 dashes
  return 0;
 }
});

This comparison function will split the elements on the dash character, and sort them based on the third part of the string if they have 3 dashes. If the elements do not have 3 dashes, they will be left in their original order.

You can also use the localeCompare function to compare the elements and sort them based on their lexicographic order:

myArray.sort(function(a, b) {
// Check if both elements have 3 dashes
 if (a.split("-").length === 3 && b.split("-").length === 3) {
     // Sort the elements based on their lexicographic order
    return a.localeCompare(b);
 } else {
    // Leave the elements in their original order if they do not have 3 dashes
    return 0;
 }
});

This will sort the elements that have 3 dashes in lexicographic order, while leaving the other elements in their original order.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading