string sort in javascript code example

Example 1: sorting array from highest to lowest javascript

// Sort an array of numbers 
let numbers = [5, 13, 1, 44, 32, 15, 500]

// Lowest to highest
let lowestToHighest = numbers.sort((a, b) => a - b);
//Output: [1,5,13,15,32,44,500]

//Highest to lowest
let highestToLowest = numbers.sort((a, b) => b-a);
//Output: [500,44,32,15,13,5,1]

Example 2: sort a string in javascript

var string='ACBacb';
var sortedString = string.split('').sort().join('');

Example 3: javascript sort

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]

Example 4: string sort javascript

var names = ["Peter", "Emma", "Jack", "Mia"];
var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]

Example 5: js string sort

if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;