Home > Mobile >  Sort only strings from an array that meets the criteria
Sort only strings from an array that meets the criteria

Time:12-31

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

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

CodePudding user response:

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.

CodePudding user response:

I would return 0 if any of the strings is of a different format and compare them otherwise

const array = [
  '3040-200021',
  '4502-Frac 01',
  '4504-Frac 16-J-10370',
  '4504-Frac 16-J-10224',
  'test 123'
]

const regex = /^\d{4}-Frac \d{2}-J-\d{5}$/

const sorted = [...array].sort((a, b) => {
  if (!a.match(regex) || !b.match(regex)) return 0
  return a.localeCompare(b)
})

console.log(sorted)

  • Related