JAVASCRIPT
ascending and descending val in array using js
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Sort to reverse from an array in javascript
const friends = ["Abir", "Ashik", "Alif", "Alfi", "Shafi", "Kafi"];
const friendsSort = friends.sort();
const friendsReverse = friendsSort.reverse();
console.log(friendsReverse);
//Output: [ 'Shafi', 'Kafi', 'Ashik', 'Alif', 'Alfi', 'Abir' ]
javascript ascending and descending
// ascending and discending for number
const arr1 = [21, 2100, 2, 35000];
const arr2 = [21, 2100, 2, 35000];
let ascN = arr1.sort((f, s) => f - s);
let dscN = arr2.sort((f, s) => s - f);
// ascending and discending for string
const arr3 = ['21', '2100', '2', '35000'];
const arr4 = ['21', '2100', '2', '35000'];
let ascS = arr3.sort((f, s) => f.length - s.length);
let dscS = arr4.sort((f, s) => s.length - f.length);
javascript sort Array descending order
//used arraow functions
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
const sortYears = arr =>{
arr.sort((a,b)=>{return b-a})
return arr
}
console.log(sortYears(years))
// Should print [ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922 ]
sort array descending
testsSortedByNome = tests.sort((a, b) => (a.nome > b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome > b.cognome ? -1 : 1));
array sorting descending
employees.sort((a, b) => b.age - a.age);
employees.forEach((e) => {
console.log(`${e.firstName} ${e.lastName} ${e.age}`);
});
Code language: JavaScript (javascript)