Javascript : Sort Array of String Ascending and Given Matching Character

Using JavaScript Array functions we can achieve Sorting of Ascending, Descending and Sort by Match String. This sample program uses JavaScript array “sort()”, “reverse()”, and “concat” function sorting.

Example: 

var listArray = [
    'Trivandram',
    'Chennai',
    'Madurai',
    'Cochin',
    'Palakkad',
    'Coimbatore',
    'Calicut',
    'Bangalore'
];
 
function sortByGivenMatchingString(match, sortList) {
    var first = [];
    var temp = [];
    for (var i = 0; i < sortList.length; i++) {
        realStr = sortList[i].toLowerCase();
        if (realStr.indexOf(match) === 0) {
            first.push(sortList[i]);
        } else {
            temp.push(sortList[i]);
        }
    }
    first.sort();
    temp.sort();
    return(first.concat(temp));
}
 
// Sort By Default Ascending.
var matchString = '';
var formatResult = sortByGivenMatchingString(matchString.toLowerCase(), listArray);
console.log(formatResult);
 
// Ascending Output:
[ 'Bangalore',
  'Calicut',
  'Chennai',
  'Cochin',
  'Coimbatore',
  'Madurai',
  'Palakkad',
  'Trivandram' ]
 
// Sort By Default Descending.
var matchString = '';
var formatResult = sortByGivenMatchingString(matchString.toLowerCase(), listArray);
console.log(formatResult.reverse());
 
// Descending Output:
[ 'Trivandram',
  'Palakkad',
  'Madurai',
  'Coimbatore',
  'Cochin',
  'Chennai',
  'Calicut',
  'Bangalore' ]
 
// Sort Character 'C'.
var matchString = 'C';
var formatResult = sortByGivenMatchingString(matchString.toLowerCase(), listArray);
console.log(formatResult);
 
// Sorting using "c" Character
[ 'Calicut',
  'Chennai',
  'Cochin',
  'Coimbatore',
  'Bangalore',
  'Madurai',
  'Palakkad',
  'Trivandram' ]
Category: