rohit13807
rohit13807

Reputation: 595

pass array to sort using function

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,

Upvotes: 0

Views: 56

Answers (2)

Dubas
Dubas

Reputation: 2876

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

Upvotes: 0

Beginner
Beginner

Reputation: 9095

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))

Upvotes: 1

Related Questions