javascript sorting array of objects string code example
Example 1: javascript sort array of objects
const books = [
{id: 1, name: 'The Lord of the Rings'},
{id: 2, name: 'A Tale of Two Cities'},
{id: 3, name: 'Don Quixote'},
{id: 4, name: 'The Hobbit'}
]
compareObjects(object1, object2, key) {
const obj1 = object1[key].toUpperCase()
const obj2 = object2[key].toUpperCase()
if (obj1 < obj2) {
return -1
}
if (obj1 > obj2) {
return 1
}
return 0
}
books.sort((book1, book2) => {
return compareObjects(book1, book2, 'name')
})
Example 2: js sort array of objects
const drinks1 = [
{name: 'lemonade', price: 90},
{name: 'lime', price: 432},
{name: 'peach', price: 23}
];
function sortDrinkByPrice(drinks) {
return drinks.sort((a, b) => a.price - b.price);
}
Example 3: javascript sort array of objects
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)
let arr3 = sortObjectArray({ arr, field: 'age', order: 'asc' })
console.log(arr3)