Example 1: sorting of arraray's number element in javascript
let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort((a, b) => a - b);
console.log(numbers);
Example 2: javascript sort
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort();
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
});
Example 3: sorting program in c
#include<stdio.h>
int main(){
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=0;i<count;i++){
for(j=i+1;j<count;j++){
if(number[i]>number[j]){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Example 4: 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 5: 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 6: sort() function example JavaScript
function ascendingOrder(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
ascendingOrder([1, 5, 2, 3, 4]);