sort string array javascript code example

Example 1: javascript sort alphabetically

var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort(function (a, b) {
  return a.localeCompare(b); //using String.prototype.localCompare()
});

// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']

Example 2: sort array by string length javascript

function sortByLength(arr) {
   return arr.sort((x,y) => x.length - y.length);
}

Example 3: 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 4: javascript sort array smallest to largest

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);

Example 5: javascript order by string array

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

Example 6: js order string

// function that returns a string in alphabetical order
function reorderStr(str) {
	return [...str].sort().join('');
}
console.log(reorderStr("hacker"));	//"acehkr"
console.log(reorderStr("javascript"));//"aacijprstv"