Home > Software design >  How to ignore special characters in string sorting in Javascript
How to ignore special characters in string sorting in Javascript

Time:12-19

Is it possible in Javascript to sort an array of strings by ignoring special characters in the array items? For example, if I have the following array:

const fruits = ["Banana", "@Orange", "Apple", "$Mango","apricot"];

and I use fruits.sort((a,b)=>a.localeCompare(b)), to sort the array, I receive the following result:

["$Mango","@Orange","Apple","apricot","Banana"]

But what I want is ["Apple","apricot","Banana","$Mango","@Orange"]

Can someone please suggest how to achieve this?

CodePudding user response:

Remove the characters from the strings before you compare them.

const specialChars = /a regular expression that expresses your definition of "special"/g;
fruits.sort(
    (a,b) => 
        a.replace(specialChars, "")
         .localeCompare(
             b.replace(specialChars, "")
         )
);

CodePudding user response:

The process would be simple - Just remove special char and then compare.

var fruits =  [".Banana", "@Orange", "Apple", "$Mango","apricot"];

fruits.sort(function (a, b) {
  function getRaw(s) {
    return s.replace(/[&\/\\#, ()$~%!.„'":*‚^_¤?<>|@ª{«»§}©®™ ]/g,'').trim();  
   }
    return getRaw(a).localeCompare(getRaw(b));
  });

 console.log(fruits);
  • Related