This post was originally published on webinuse.com
Welcome to JavaScript sort method part 2. We already wrote on how to sort strings and numbers. Today we are talking about how can we sort objects.
Similar to arrays, we can sort objects by some key.
const obj = [
{id: 225, name: 'John'},
{id: 123, name: 'Aida'},
{id: 897, name: 'Elisabeth'},
{id: 242, name: 'Jamal'}
]
obj.sort(function(a,b) {
if (a.id > b.id) {
return 1;
}
return -1;
})
//Result
/*[
{id: 123, name: 'Aida'},
{id: 225, name: 'John'},
{id: 242, name: 'Jamal'},
{id: 897, name: 'Elisabeth'}
]
*/
In the previous example, we sorted object by obj.id
. We can do the same, but with obj.name
.
const obj = [
{id: 225, name: 'John'},
{id: 123, name: 'Aida'},
{id: 897, name: 'Elisabeth'},
{id: 242, name: 'Jamal'}
]
obj.sort(function(a,b) {
if (a.name > b.name) {
return 1;
}
return -1;
})
//Result
/*[
{id: 123, name: 'Aida'},
{id: 897, name: 'Elisabeth'},
{id: 242, name: 'Jamal'},
{id: 225, name: 'John'}
]
*/
How to use arrow functions with JavaScript sort method?
ES2015 introduced arrow function expressions. An arrow function can help us shorten compare function
.
Let's take a look at some examples. We will create previous examples (and from part 1) with arrow functions instead of "normal" functions.
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
//Result:
// [1, 2, 3, 4, 5]
numbers.sort(a, b) => b - a);
console.log(numbers);
//Result:
// [5, 4, 3, 2, 1]
numbers.sort(a, b) => b === a);
console.log(numbers);
//Result:
// [4, 2, 5, 1, 3]
const obj = [
{id: 225, name: 'John'},
{id: 123, name: 'Aida'},
{id: 897, name: 'Elisabeth'},
{id: 242, name: 'Jamal'}
]
obj.sort((a,b) => (a.id > b.id) ? 1 : -1)
//Result
/*[
{id: 123, name: 'Aida'},
{id: 225, name: 'John'},
{id: 242, name: 'Jamal'},
{id: 897, name: 'Elisabeth'}
]
*/
obj.sort((a,b) => (a.name > b.name) ? 1 : -1)
//Result
/*[
{id: 123, name: 'Aida'},
{id: 225, name: 'John'},
{id: 242, name: 'Jamal'},
{id: 897, name: 'Elisabeth'}
]
*/
If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like JavaScript sort method – part 1.
Top comments (0)