Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript string array custom sorting

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

like image 277
tsagbaaa111 Avatar asked Apr 12 '26 23:04

tsagbaaa111


1 Answers

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; }
like image 82
Nina Scholz Avatar answered Apr 14 '26 12:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!