JavaScript string array custom sorting

tsagbaaa111 :

Hi there I am trying to implement a custom string comparator function in JavaScript. There are some special values that I want them to be always before other, with the rest just being alphabetically sorted. For example, if I have an array ("very important" "important", "Less important") are three special values(should have order as above)

    ["e","c","Less Important","d","Very Important","a",null,"Important","b","Very Important"]. 

After sorting , the array should be( if there's a null or undefined value, need to place in the last)

    ["Very Important", "Very Important", "Important", "Less Important" "a","b","c","d","e",null]  

how can I write a comparator function for the requirement above? (im using a comparator api of a library, so i cannot sort the array but need to implement the logic with a comparator( like compareTo in java which returns 0,1,-1)

thanks a lot

Nina Scholz :

You could

  • move null values to bottom,
  • move 'Very Important' strings to top,
  • move Important' strings to top and
  • sort the rest ascending.

var array = ["Important", "e", "c", "d", "Very Important", "a", null, "b", "Very Important"];

array.sort((a, b) =>
    (a === null) - (b === null) ||
    (b === 'Very Important') - (a === 'Very Important') ||
    (b === 'Important') - (a === 'Important') ||
    a > b || -(a < b)
);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12005&siteId=1