//Higher order function for sorting
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
return a - b
});
////HOF/////
numArray.sort(function(a, b){
return a - b
});
//output >> [1 ,5 , 10 ,25 ,40 ,100]
function eq(x, y) {
if (x < y) return -1;
else if (x > y) return 1;
else return 0;
}
let num = new Array(8, 50, 2, 34, 12, 8);
num.sort(eq);
let text = num.join();
document.write(text);
// student array
let students = ['John', 'Jane', 'Mary', 'Mark', 'Bob'];
// sort the array in ascending order
students.sort();
// ? result = ['Bob', 'Jane', 'John', 'Mark', 'Mary']
// sort the array in descending order
students.sort().reverse();
// ? result = ['Mary', 'Mark', 'John', 'Jane', 'Bob']
let arr = [1,2,3,3,4]
arr.sort() => sorts in ascending order from right to left
// You can sort in custom orders by defining a custom comparison function
// ex:
arr.sort(function compareNumbers(firstNumber, secondNumber){
/*
if a negative number is returned, firstNumber will be the first number in the output
if a positive number is returned, secondNumber will be the first number in the output
if a 0 is returned, it will default to returning them in the position they're already in
*/
// ascending order
// return firstNumber - secondNumber
// descending order
//return secondNumber - firstNumber
// Always want 3's to come first:
/*
if firstNumber === 3{
return -1
}
if secondNumber === 3{
return 1
}
return secondNumber - firstNumber
*/
})
Scanner sc = new Scanner(System.in);
int[] arr = new int[6];
System.out.println("Enter the elements in the array");
for (int i = 0;i< arr.length;i++){
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
for (int values : arr){
System.out.print(values +" ");
}
let persolize=[ { key: 'speakers', view: 10 }, { key: 'test', view: 5 } ]
persolize.sort((a,b) => a.view - b.view);
//If it only array and not an array object, use below statement
//persolize.sort((a,b) => a - b);