3

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

0

1 Answer 1

2

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; }

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! How does the function take care of the second special value "Important"? also how can i make your logic into a comparator function that returns -1,0,1?
the deltas returns a numerical value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.