michaelp0730
11/20/2019 - 12:03 AM

JS string and number sorting - ascending & descending

Functions for sorting strings and numbers in ascending and descending order with JavaScript

var nums = [111, 47, 54, 33, 12, 9, 5];
console.log('nums: ', nums);

var names = ['michael', 'jessica', 'ava', 'elise', 'enzo'];
console.log('names: ', names);

var sortedNums = nums.sort(function(a, b) {
  return a - b;
});
console.log('sortedNums: ', sortedNums);

var sortedNames = names.sort(function(a, b) {
  if (a > b) return 1;
  if (a < b) return -1;
  return 0;
});
console.log('sortedNames: ', sortedNames);

var descNums = nums.sort(function(a, b) {
  return b - a;
});
console.log('descNums: ', descNums);

var descNames = names.sort(function(a, b) {
  if (a > b) return -1;
  if (a < b) return 1;
  return 0;
});
console.log('descNames: ', descNames);