Sort an array of objects by property in JavaScript
Sorting an array of objects by a string property value in JavaScript can be accomplished in several ways, each with its own use cases and nuances. Below are some of the most common methods, including using the Array.prototype.sort()
, Array.prototype.sort()
with localeCompare()
, and using libraries like Lodash if you’re working in an environment where external libraries are acceptable.
1. Using Array.prototype.sort()
The sort()
method sorts the elements of an array in place and returns the array. The default sort order is according to string Unicode code points. Therefore, when sorting by a string property, it works well for simple cases.
const array = [
{name: 'John', age: 25},
{name: 'Alice', age: 30},
{name: 'Bob', age: 20}
];
array.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
console.log(array);
2. Using Array.prototype.sort()
with localeCompare()
This method is particularly useful when you need to sort strings that include special characters or are case-insensitive, or when you need to sort in a specific locale.
const array = [
{name: 'John', age: 25},
{name: 'Alice', age: 30},
{name: 'Bob', age: 20}
];
array.sort((a, b) => a.name.localeCompare(b.name));
console.log(array);
3. Using Arrow Functions for Simplicity
If you prefer more concise code, you can use arrow functions, especially when sorting by a single property in ascending order.
const array = [
{name: 'John', age: 25},
{name: 'Alice', age: 30},
{name: 'Bob', age: 20}
];
array.sort((a, b) => a.name.localeCompare(b.name));
console.log(array);
Or, if you want it even more concise but still readable:
array.sort(({name: a}, {name: b}) => a.localeCompare(b));
4. Using Lodash
If you’re working in an environment where Lodash is available, you can use its sortBy
function for sorting.
const _ = require('lodash');
const array = [
{name: 'John', age: 25},
{name: 'Alice', age: 30},
{name: 'Bob', age: 20}
];
const sortedArray = _.sortBy(array, 'name');
console.log(sortedArray);
Latest blog posts
Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.