Warning: session_start(): open(/tmp/sess_0ccf151c4a87f7eb9dff1c0ac2412bbf, O_RDWR) failed: Disk quota exceeded (122) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: session_start(): Failed to read session data: files (path: /tmp) in /home/wvyrfnwn/learnshareit.com/wp-content/plugins/learnpress/inc/class-lp-page-controller.php on line 1007

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 719

Warning: ftp_mkdir() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 562

Warning: ftp_nlist() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 420

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230

Warning: ftp_pwd() expects parameter 1 to be resource, null given in /home/wvyrfnwn/learnshareit.com/wp-admin/includes/class-wp-filesystem-ftpext.php on line 230
How To Sort An Array Of Objects In React - LearnShareIT

How To Sort An Array Of Objects In React

Sort an Array of Objects in React

This article lets you know how to sort an array of objects in React. Let’s see how we do it now,

Sort an array of objects in React

To sort an array in React, we use the sort() method.

Syntax:

Array.sort()

Example:

const evens = [22, 38, 6, 18, 92, 80];
evens.sort();
console.log(evens);

Output:

[ 18, 22, 38, 6, 80, 92 ]

You may find that the results are not quite what we imagined. The strange thing is that the numbers are not sorted in ascending or descending order. The reason is that the elements are converted to ‘string‘ and sorted by Unicode table.

To solve it, we will use a function in the sort() method to get the desired result. It is also the method for us to sort an array of objects in React that I want to cover in this tutorial.

Define a comparison function

In this approach, we define a function that swaps the positions of the elements and returns the desired result.

Syntax:

sort(function compare(a, b) {
    ...
})

Take a look at this example in React:

Example 1:

export default function App() {
    const table = [
        {
            club: 'Arsenal', 
            rank: 2
        },
        {
            club: 'Liverpool', 
            rank: 3
        },
        {
            club: 'Manchester United', 
            rank: 1
        },
        {
            club: 'Chelsea',
            rank: 3
        }
    ];

    const orderByRankASC = [...table].sort(function compare(a, b) {
        if(a.rank > b.rank) return 1;
        if(a.rank < b.rank) return -1;
        return 0;
    });

    const orderByRankDESC = [...table].sort(function compare(a,b) {
        if(a.rank > b.rank) return -1;
        if(a.rank < b.rank) return 1;
        return 0;
    });

    return (
        <div class="container">
            <div class="row">
                <div class="col">
                    <h2>ASCENDING</h2>
                    <div>
                        {orderByRankASC.map(element => {
                            return (
                                <div key={element.id}>
                                    <h2>club: {element.club}</h2>
                                    <h2>rank: {element.rank}</h2>
                                    <hr />
                                </div>
                            );
                        })}
                    </div>
                </div>
                <div class="col">
                    <h2>DESCENDING</h2>
                    <div>
                        {orderByRankDESC.map(element => {
                            return (
                                <div key={element.id}>
                                    <h2>club: {element.club}</h2>
                                    <h2>rank: {element.rank}</h2>
                                    <hr />
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </div>
    );
}

Output:

As you can see in the output, using the compare() function inside the sort() method will help us get the exact result of the sorted sequence.

Let me explain what just happened in the above program:

We define a function named ‘compare‘ which takes two arguments: a and b. a and b are the two elements to be compared.

Specifically, in this example, they are objects, and we sort them based on their ‘rank’ attribute.

If the return value of the comparison function is:

  • Less than 0 – a will come before b
  • Greater than 0 – b will come before a
  • Equal to 0 – Will not change positions

Use the arrow function

If you don’t want to declare a function like the above approach, there is another way for you. That is using the arrow function. This way of writing is more concise, but if anyone is unfamiliar or has never used it, it may be a bit confusing.

Syntax:

sort((a, b) => {
    ...
})

Example:

export default function App() {
    const table = [
        {
            club: 'Arsenal', 
            rank: 2
        },
        {
            club: 'Liverpool', 
            rank: 3
        },
        {
            club: 'Manchester United', 
            rank: 1
        },
        {
            club: 'Chelsea',
            rank: 3
        }
    ];

    const orderByClubASC = [...table].sort((a, b) => (a.club > b.club ? 1 : -1));
    const orderByClubDESC = [...table].sort((a, b) => (a.club > b.club ? -1 : 1));

    return (
        <div class="container">
            <div class="row">
                <div class="col">
                    <h2>ASCENDING</h2>
                    <div>
                        {orderByClubASC.map(element => {
                            return (
                                <div key={element.id}>
                                    <h2>club: {element.club}</h2>
                                    <h2>rank: {element.rank}</h2>
                                    <hr />
                                </div>
                            );
                        })}
                    </div>
                </div>
                <div class="col">
                    <h2>DESCENDING</h2>
                    <div>
                        {orderByClubDESC.map(element => {
                            return (
                                <div key={element.id}>
                                    <h2>club: {element.club}</h2>
                                    <h2>rank: {element.rank}</h2>
                                    <hr />
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </div>
    );
}

Output:

In this example, I sort the object based on the ‘club‘ property, so you can see that we are comparing not only numbers but also strings alphabetically.

We can change the content inside the comparison function to get the desired result. In both examples, I’ve demonstrated ascending and descending sort on two properties: ‘club’ and ‘ranking’. You can customize the comparison function to specify how the elements are sorted.

Summary

I have provided some methods to help you sort an array of objects in React. Thank you for reading and hopefully it’s helpful for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *