0

I want to pass data array that is coming from function to sort. For example :

const DEFAULT_COMPETITORS = [ 'Seamless/Grubhub', 'test'];

DEFAULT_COMPETITORS.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
});

Above is working fine. But I want data from function instead of DEFAULT_COMPETITORS const. I want like below:

My data is coming in getAllCompetitors instead of const.

function getAllCompetitors() {
    $.ajax({
        url: '/salescrm/getTopCompetitorsList',
        type: 'POST',
        success: function(data) {
            console.log('getAllCompetitors data: ',data);
            response(data);
        },
        error: function(data) {
            console.log('data error: ',data);
        }
    });
 }

getAllCompetitors.sort(function (a, b) {
    return a.toLowerCase().localeCompare(b.toLowerCase());
}); 

Hope you guys got.. could any please help me

Thanks in advance,

LuFFy
  • 8,799
  • 10
  • 41
  • 59
rohit13807
  • 605
  • 8
  • 19
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Aug 08 '18 at 06:51

2 Answers2

1

i hope this will work

function getAllCompetitors() {
    return $.ajax({
        url: '/salescrm/getTopCompetitorsList',
        type: 'POST',
    });
 }


getAllCompetitors()
      .then(res => {
          // you can sort the data 
          let sortedData = res.sort(function (a, b) {
            return a.toLowerCase().localeCompare(b.toLowerCase());
        }); 
        console.log("sortedData once ajax call made the success",sortedData)
      })
      .fail(err= > console.log(err))
Learner
  • 8,379
  • 7
  • 44
  • 82
  • { "message": "SyntaxError: expected expression, got '>'", "filename": "https://stacksnippets.net/js", "lineno": 29, "colno": 17 } – jonatjano Aug 13 '18 at 07:39
  • you need to try the code in your project , because you are using url key as "/salescrm/" so here it will take the root which is " https://stackoverflow.com". just try in your domain so it will take the root domain url – Learner Aug 13 '18 at 07:53
  • ho that's why. Thank for the clarification ;) – jonatjano Aug 13 '18 at 08:01
  • happy coding :) – Learner Aug 13 '18 at 08:02
0

Here is a simple example:

Over any array you could use the funcion .sort() to sort by default sorting rules or using .sort with a function to use a custom sorting rules provided by you in the method

Default sorting:

var items = ['baa', 'aaa', 'aba',"Caa"];
var sortedItems = items.sort();
console.log(sortedItems);

Custom sorting:

var items = ['baa', 'aaa', 'aba','Caa'];
var sortedItems = items.sort(function(item1,item2){
     // Locale text case insensitive compare
     return item1.toLowerCase().localeCompare(item2.toLowerCase());
});
console.log(sortedItems);

Mozilla Sort documentation

Dubas
  • 2,855
  • 1
  • 25
  • 37