Example 1: javascript string array sort alphabetically
var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
items.sort((a, b) =>
a.localeCompare(b)
);
Example 2: javascript sort array strings alphabetically
objArray.sort(function(a, b) {
return a.localeCompare(b);
});
Example 3: how the sort function works javascript
const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();
console.log(sorted);
const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
return a - b;
});
console.log(sortedNums);
Example 4: sorting in js
var arr = [23, 34343, 1, 5, 90, 9]
var sortedArr = [];
arr.forEach(x => {
if (sortedArr.length == 0)
sortedArr.push(x)
else {
if (sortedArr[0] > x) sortedArr.unshift(x)
else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
}
})
console.log(sortedArr);
console.log(arr.sort((a,b)=>{
return a-b;
}));
Example 5: sort function explained javascript
var sortedArray = myArray.sort(function(a,b){
if (a.name < b.name)
return -1;
else if (a.name == b.name)
return 0;
else
return 1;
});
Example 6: JavaScript Sorting Arrays
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();