Reputation: 33
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
Upvotes: 3
Views: 541
Reputation: 386680
You could
null
values to bottom,'Very Important'
strings to top,Important'
strings to top andvar 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; }
Upvotes: 2