Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to custom sort in JavaScript? Not alphabetical or numerical

I have many lists that need to be sorted according to specified interest. Alphabetical and numerical sorts using the array of values will not work.

For an example. The below cities, need to appear in this order. How can I accomplish this using JavaScript? Is there a way, I can represent each city with a numerical value then use the numerical values to sort the cities to the desired order below?

Salisbury, High Point, Wake, Charlotte, Raleigh, Cary, Wilson

like image 433
user2267035 Avatar asked Oct 17 '25 13:10

user2267035


2 Answers

Put the keys into a map:

var cityScores = {
  Salisbury: 5, High Point: 10, Wake: 15, Charlotte: 20, Raleigh: 25, Cary: 30, Wilson: 35
};

Then when you sort you can just refer to the scorings in that object:

cityList.sort(function(city1, city2) {
  return cityScores[city1] - cityScores[city2];
});

If the array is an array of objects with the city in it, then:

objectList.sort(function(o1, o2) {
  return cityScores[o1.city] - cityScores[o2.city];
});
like image 110
Pointy Avatar answered Oct 20 '25 04:10

Pointy


A solution for more than only the listed words, with precedence of the listed words.

var data = [
        'Salisbury', 'Charlotte', 'Frankfurt', 'Düsseldorf', 'Raleigh',
        'Cary', 'Wilson', 'High Point', 'Wake', 'New Jersey'
    ],
    customSort = [
        'Salisbury', 'High Point', 'Wake', 'Charlotte', 'Raleigh',
        'Cary', 'Wilson'
    ],
    customLookup = customSort.reduce(function (r, a, i) {
        r[a] = ('000'+i).slice(-4); return r;
    }, {}),
    customSortFn = function (a, b) {
        return (customLookup[a] || a).localeCompare(customLookup[b] || b);
    };

document.write('<pre>' + JSON.stringify(data.sort(customSortFn), 0, 4) + '</pre>');
like image 31
Nina Scholz Avatar answered Oct 20 '25 04:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!