Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort an array of objects based on scores – Javascript

I have an array of objects that contain the data I want to sort (it has more properties), like so:

[
    {
        "data": {
            "id": "green"
        }
    },
    {
        "data": {
            "id": "red"
        }
    },
    {
        "data": {
            "id": "blue"
        }
    }
]

id is a nested property I need to use in order to sort based on scores provided from a different object like so:

{
    "green": 5,
    "red": 3,
    "blue": 8
}

I’m trying to find the best way to sort my array of object, however no success so far.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can sort them like this:
https://jsfiddle.net/Ldvja31t/1/

const scores = {
    "green": 5,
    "red": 3,
    "blue": 8
};

const myData = [
    {
        "data": {
            "id": "green"
        }
    },
    {
        "data": {
            "id": "red"
        }
    },
    {
        "data": {
            "id": "blue"
        }
    }
];

myData.sort((d1, d2) => {
    return scores[d1.data.id] - scores[d2.data.id]
});

console.log(myData)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading