1

I am trying to call a shared comparer function from an array.sort to sort 2 different arrays.

if i have:

projects.sort(
        function(a, b){
          var x = a.name.toLowerCase();
          var y = b.name.toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

and

products.sort(
        function(a, b){
          var x = a.name.toLowerCase();
          var y = b.name.toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
        });

how can i do this?

projects.sort(sortArray());
products.sort(sortArray());
1
  • 1
    Don't put the parentheses after sortArray: projects.sort(sortArray) Commented Jul 26, 2018 at 21:33

2 Answers 2

3

Create a named function:

function compare(a, b){
  var x = a.name.toLowerCase();
  var y = b.name.toLowerCase();
  if (x < y) {return -1;}
  if (x > y) {return 1;}
  return 0;
}

Then you can reference this function when you call sort:

projects.sort(compare);
products.sort(compare);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, Peter! for some reason when i tried this it didn't work. It's working now, beautifully. much appreciated for your quick response.
0
function sortItems(a,b) {
  var   x = a.name.toLowerCase(),
        y = b.name.toLowerCase()

  return x.localeCompare(y);
 }

// Then use this
projects.sort(sortItems);
products.sort(sortItems);

1 Comment

Please add an explanation to your answer, it will help users with their future searches.

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.