Introduction
When working with arrays of objects in JavaScript, a common task is to sort these arrays based on one or more properties within the objects. This tutorial will guide you through different methods to achieve this, using both native JavaScript and additional libraries like Underscore.js.
Sorting Arrays Using Native JavaScript
JavaScript provides a sort()
method that can be used with a custom comparator function. This is essential for sorting arrays of objects based on specific properties.
Basic Sorting by String Property
Consider an array of objects where each object has a last_nom
property:
var objs = [
{ first_nom: 'Laszlo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
To sort this array by the last_nom
property, define a comparison function:
function compare(a, b) {
if (a.last_nom < b.last_nom) return -1;
if (a.last_nom > b.last_nom) return 1;
return 0;
}
objs.sort(compare);
Alternatively, you can use an inline arrow function for a more concise approach:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
This method is particularly useful as localeCompare()
handles string comparison, considering locale-specific rules.
Dynamic Sorting Function
For greater flexibility, create a dynamic sorting function that can sort based on any property:
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === '-') {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
let result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
};
}
var People = [
{ Name: "Name", Surname: "Surname" },
{ Name: "AAA", Surname: "ZZZ" },
{ Name: "Name", Surname: "AAA" }
];
People.sort(dynamicSort("Name"));
People.sort(dynamicSort("-Surname")); // For descending order
Sorting with Multiple Criteria
To sort by multiple properties, extend the dynamic sorting function:
function dynamicSortMultiple() {
var props = arguments;
return function(obj1, obj2) {
let i = 0, result = 0, numberOfProperties = props.length;
while (result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
};
}
People.sort(dynamicSortMultiple("Name", "-Surname"));
Using ES6 Features
ES6 introduces concise syntax for sorting using arrow functions and localeCompare()
:
objs.sort((a, b) => a.last_nom.localeCompare(b.last_nom));
This approach is cleaner and leverages modern JavaScript features.
Sorting with Underscore.js
For those preferring to use external libraries, Underscore.js offers a straightforward way to sort arrays:
var _ = require('underscore');
var sortedObjs = _.sortBy(objs, 'first_nom');
This method is ideal for developers already using the library in their projects.
Case Sensitivity Considerations
When sorting strings, consider case sensitivity. For case-insensitive sorting:
arr.sort((a, b) => a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1);
This ensures that comparisons are not affected by character casing.
Conclusion
Sorting arrays of objects in JavaScript can be accomplished using native methods or external libraries. Understanding how to create custom comparator functions and utilizing ES6 features will enhance your ability to manipulate data effectively. Whether you need simple sorting or complex multi-criteria arrangements, these techniques provide the flexibility required for most applications.