javascript sort array with objects
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest first
javascript sort array with objects
var array = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "Jake", age: 25}
];
array.sort(function(a, b) {
return a.age - b.age;
}); // Sort youngest first
javascript sort array of objects
// Handles mix-cased strings and numbers with option for setting order
const sortObjectArray = ({ arr, field, order = 'desc' }) => {
arr.sort(function(a, b) {
const fieldA = typeof a[field] === 'string' ? a[field].toLowerCase() : a[field]
const fieldB = typeof b[field] === 'string' ? b[field].toLowerCase() : b[field]
let result
if (order === 'desc') {
result = fieldA > fieldB ? 1 : -1
} else {
result = fieldA < fieldB ? 1 : -1
}
return result
})
return arr
}
let arr = [
{name: "John", age: 34},
{name: "Peter", age: 54},
{name: "jake", age: 25}
]
let arr2 = sortObjectArray({ arr, field: 'name'})
console.log(arr2)
/*
[
{ age: 25, name: "jake"},
{ age: 34, name: "John" },
{ age: 54, name: "Peter" }
]
*/
let arr3 = sortObjectArray({ arr, field: 'age', order: 'asc' })
console.log(arr3)
/*
[
{ age: 54, name: "Peter" },
{ age: 34, name: "John" },
{ age: 25, name: "jake"}
]
*/
sort() object values javascript
list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )
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