JS array sort
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
JS array sort
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
js sort
strData = ["banana", "apple", "zebra", "jos"];
numData = [1, 3, 2, 5, 6];
objData = [
{ name: 'Alex', age: 20 },
{ name: 'Karlsson', age: 19 },
{ name: 'Noah', age: 21 },
];
// sort str alfabeticly (a-z)
strData.sort((a,b) => {
return a === b ? 0 : a < b ? -1 : 1
});
console.log(strData)
// sort Objdata uppifrån å ner (ålder 19-21)
objData.sort((a,b) => a.age - b.age)
console.log(objData);
// Small number to large number
numData.sort()
console.log(numData);
// Large number to small number
numData.sort((a,b) => b-a)
console.log(numData);
sort javascript array
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
javascript sort
var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
var objs = [
{name: "Peter", age: 35},
{name: "Emma", age: 21},
{name: "Jack", age: 53}
];
objs.sort(function(a, b) {
return a.age - b.age;
}); // Sort by age (lowest first)
sort array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
js sort an array
// sort an array
// by drinks: lowest to highest
function sortDrinkByPrice(drinks) {
return drinks.sort((a, b) => {
return a.price - b.price;
});
}
// parse the array as parameters within the function
console.log(sortDrinkByPrice([{name: "lemonade", price: 50},{name: "lime", price: 10}]));
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us