How to sort object property by values in JavaScript?

Aug 26, 2022 . Admin



Hello dev,

I am going to explain to you an example of how to sort object property by values in javascript. step by step explain Sort JavaScript Object Property by Values. step by step explain javascript object property sort by values. Here you will learn to explain how to sort object property of javascript by values.

We can use JavaScript methods that are built into the Object constructor to get the keys and values of an object as an array We use the Object.entries method to get an array of array of key-value pairs from the ages object, the array returned from Object.entries.And then we call reduce with a callback to merge the obj object with the k and v key-value pair

Another way to sort an object’s properties by their property values is to get the keys from the Object.keys method. Object. keys only return the property name strings of the ages object, so in the sort callback, we’ve to get the value from the ages object to do the sorting. Also, we’ve to do the same thing in the reduce callback to get the object value from ages

So, let's see bellow solution:

Example : 1
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to sort object property by values in JavaScript? -  MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to sort object property by values in JavaScript? -  MyWebtuts.com</h1>

        <script type="text/javascript">

            const ages = {
            pratik: 10,
            rohit: 9,
            kohli: 30
            };

            const sorted = Object.entries(ages)
                .sort(([, v1], [, v2]) => v1 - v2)
                .reduce((obj, [k, v]) => ({
                ...obj,
                [k]: v
                }), {});
                console.log(sorted);   
        </script>
    </body>
<html>
Output:
{pratik: 9, rohit: 10, kohli: 30}
Example : 2 index.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to sort object property by values in JavaScript? -  MyWebtuts.com</title>
    </head>
    <body>
        <h1>How to sort object property by values in JavaScript? -  MyWebtuts.com</h1>

        <script type="text/javascript">

            const ages = {
            pratik: 10,
            rohit: 9,
            kohli: 30
            };

            const sorted = Object.keys(ages)
                .sort((key1, key2) => ages[key1] - ages[key2])
                .reduce((obj, key) => ({
                ...obj,
                [key]: ages[key]
                }), {});
                console.log(sorted);   
        </script>
    </body>
<html>
Output:
{pratik: 9, rohit: 10, kohli: 30}
I hope it will help you...
#Javascript