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
javascript orderby
var items = [
{ name: 'Edward', value: 21 },
{ name: 'Sharpe', value: 37 },
{ name: 'And', value: 45 },
{ name: 'The', value: -12 },
{ name: 'Magnetic', value: 13 },
{ name: 'Zeros', value: 37 }
];
// sort by value
items.sort(function (a, b) {
return a.value - b.value;
});
// sort by name
items.sort(function(a, b) {
var nameA = a.name.toUpperCase(); // ignore upper and lowercase
var nameB = b.name.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
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 js
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
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)
js sort
let numbers = [4, 10, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
// [1, 2, 3, 4, 5]
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