Skip to content
the poor coder

sort array object

Poor Man
Published
Reading time
2 min read

Sorting an array of objects can be done in a variety of ways. For example, if you want to sort the array in ascending order based on one of the objects' properties, you can use the sort() method of the array. The basic syntax for this is:

Text

        array.sort(function(a,b) {
            return a.property - b.property;
        });
    

In the above code, a and b are two elements in the array, and property is the property of the object which you are trying to sort by. This function returns a number less than 0 if a is less than b, a number greater than 0 if a is greater than b, and 0 if they are equal.

If you want to sort the array in descending order, you can use the same function, but with the parameters reversed:

Text

        array.sort(function(a,b) {
            return b.property - a.property;
        });
    

If you want to sort the array based on multiple properties, you can use the sort() method with a combination of if/else statements. For example, if you want to sort the array by two properties, property1 and property2, you can use:

Text

        array.sort(function(a,b) {
            if (a.property1 === b.property1) {
                return a.property2 - b.property2;
            } else {
                return a.property1 - b.property1;
            }
        });
    

The above code first checks if the two elements' property1 values are equal. If they are, it compares the property2 values. If they are not, it compares the property1 values.

You can also use the sort() method with the Array.from() method to convert a NodeList or other array-like object into an array. For example:

Text

        let array = Array.from(myNodeList);
        array.sort(function(a,b) {
            return a.property - b.property;
        });
    

The Array.from() method creates a new array from an array-like object, such as a NodeList. The sort() method can then be used to sort the resulting array.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC