DEV Community

Cover image for Sort an Array of Objects Ways in JavaScript
Fatemeh Paghar
Fatemeh Paghar

Posted on

Sort an Array of Objects Ways in JavaScript

Sorting arrays of objects in JavaScript is a fundamental task for developers working with complex data structures. Whether you're dealing with numeric values, strings, or dates, JavaScript provides powerful tools to efficiently organize your data. In this guide, we'll explore various methods to sort arrays of objects based on different criteria.

Sorting an Array of Objects by Numbers

When sorting an array of objects by numeric values, you can utilize the sort() method along with a custom comparison function. This function compares two objects based on a specific numeric property.

// Sample array of objects with numeric values
const numericObjects = [
    { id: 3, value: 20 },
    { id: 1, value: 10 },
    { id: 2, value: 30 }
];

// Sort the array based on the 'value' property
numericObjects.sort((a, b) => a.value - b.value);

console.log(numericObjects);
Enter fullscreen mode Exit fullscreen mode

In this example, the sort() method arranges the objects in ascending order based on the value property.

Sorting an Array of Objects by Strings

Sorting an array of objects by string values follows a similar approach. You can use the sort() method with a custom comparison function to sort objects based on a specific string property.

// Sample array of objects with string values
const stringObjects = [
    { id: 3, name: 'Charlie' },
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
];

// Sort the array based on the 'name' property
stringObjects.sort((a, b) => a.name.localeCompare(b.name));

console.log(stringObjects);

Enter fullscreen mode Exit fullscreen mode

In this example, localeCompare() is used within the comparison function to ensure proper sorting of strings in different languages.

Sorting an Array of Objects by Dates

Sorting an array of objects by dates requires special handling due to the nature of date objects. You can still utilize the sort() method with a custom comparison function tailored for dates.

// Sample array of objects with date values
const dateObjects = [
    { id: 3, date: 'December 15, 2017'},
    { id: 1, date: 'January 15, 2019'},
    { id: 2, date: 'February 15, 2011'}
];

// Sort the array based on the 'date' property
dateObjects.sort((a, b) => {
    let da = new Date(a.date),
        db = new Date(b.date);
    return da - db;
});

console.log(dateObjects);

Enter fullscreen mode Exit fullscreen mode

In this example, the sort() method compares dates directly by subtracting one from the other, which works because dates are inherently comparable in JavaScript.

Using a custom, dynamic sort function

Sort an array of objects alphabetically based on a property

const alphabetical = (arr, getter, order = 'asc') =>
  arr.sort(
    order === 'desc'
      ? (a, b) => getter(b).localeCompare(getter(a))
      : (a, b) => getter(a).localeCompare(getter(b))
  );

const people = [ { name: 'John' }, { name: 'Alice' }, { name: 'Bob' } ];
alphabetical(people, g => g.name);
// [ { name: 'Alice' }, { name: 'John' }, { name: 'Bob' } ]
alphabetical(people, g => g.name, 'desc');
// [ { name: 'Bob' }, { name: 'John' }, { name: 'Alice' } ]
Enter fullscreen mode Exit fullscreen mode

Utilizing the Array.prototype.sort() method, we can efficiently organize the array according to the designated property. Employing String.prototype.localeCompare() enables us to compare values associated with the specified property. Optionally, the order parameter, which defaults to 'asc', allows us to control the sorting direction.

This function alphabetical accepts an array arr, a getter function to extract the property for comparison, and an optional order parameter to specify the sorting direction. By default, it sorts in ascending order ('asc'), but it can be overridden to sort in descending order ('desc').

Sorting an array of objects based on specified properties and orders

function dynamicSort(array, sortBy) {
    return array.sort((a, b) => {
        return sortBy.reduce((result, current) => {
            if (result !== 0) return result;

            const { property, order = 'asc' } = current;

            let comparison = 0;
            if (a[property] > b[property]) {
                comparison = 1;
            } else if (a[property] < b[property]) {
                comparison = -1;
            }

            if (order === 'desc') {
                comparison *= -1;
            }

            return comparison;
        }, 0);
    });
}

// Example usage:
const data = [
    { name: 'John', age: 30 },
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 35 }
];

const sortedData = dynamicSort(data, [
    { property: 'age', order: 'asc' },
    { property: 'name', order: 'desc' }
]);

console.log(sortedData);
//
[
  { name: 'Alice', age: 25 },
  { name: 'John', age: 30 },
  { name: 'Bob', age: 35 }
]


Enter fullscreen mode Exit fullscreen mode

Here's how it works:
Parameters: The function takes two parameters:

  • array: This is the array of objects that you want to sort.
  • sortBy: This is an array of objects, each specifying a property to sort by and its corresponding sort order. If the sort order is not provided, it defaults to ascending ('asc').

Sorting Mechanism: The array.sort() method is used to perform the sorting. Within the sorting callback function, the sortBy array is iterated over using the Array.reduce() method.

Comparison: For each property specified in sortBy, a comparison function is applied. This function compares the corresponding property values of two objects (a and b) being compared.

Sorting Order: The order property of each sortBy item determines whether the sorting should be in ascending ('asc') or descending ('desc') order. If the order is 'desc', the comparison result is negated to reverse the sorting order.

Final Sorting Result: The sorting process continues until a non-zero comparison result is found, which determines the final order of the objects in the sorted array.

Conclusion

Sorting arrays of objects in JavaScript is a common task that can be accomplished using the sort() method along with custom comparison functions. By understanding how to sort arrays based on numeric values, strings, and dates, you can effectively manage complex data structures in your JavaScript applications. Experiment with these techniques to efficiently organize your data according to your specific requirements.

References:

Top comments (0)