string sort javascript code example
Example 1: javascript order by string array
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
Example 2: sort a string in javascript
var string='ACBacb';
var sortedString = string.split('').sort().join('');
Example 3: array sort js
arr = ['width', 'score', done', 'neither' ]
arr.sort() // results to ["done", "neither", "score", "width"]
arr.sort((a,b) => a.localeCompare(b))
// if a-b (based on their unicode values) produces a negative value,
// a comes before b, the reverse if positive, and as is if zero
//When you sort an array with .sort(), it assumes that you are sorting strings
//. When sorting numbers, the default behavior will not sort them properly.
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
// b - a will give you the reverse order of the sorted items
//this explnation in not mine
Example 4: sort by ascending javascript
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
Example 5: arr.sort
//sort an array of strings
var fruitSalad = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
//sort an array of numbers
var scores = [1, 10, 2, 21];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
//sorts an array of words
var randomThings = ['word', 'Word', '1 Word', '2 Words'];
randomThings.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
Example 6: string sort javascript
var names = ["Peter", "Emma", "Jack", "Mia"];
var sorted = names.sort(); // ["Emma", "Jack", "Mia", "Peter"]