简体   繁体   中英

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.

Javascripts built-in sort function has a optional comparison function parameter. The following code utilizes this function to solve your problem:

 var array = [ { "data": { "id": "green" } }, { "data": { "id": "red" } }, { "data": { "id": "blue" } } ]; var scores = { "green": 5, "red": 3, "blue": 8 }; array.sort((a, b) => (scores[a.data.id] - scores[b.data.id])); console.log(array);

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)

The two answers that were given should work fine. However I would also like to add you could use an Enum. Example

Heres a separate example of an enum usage and sorting it in an array of objects

const enum Order {
    Start = 'Start',
    Run = 'Run',
    End = 'End',
}

const predicate = (a, b) => {
    const map = {};
    map[Order.Start] = 1;
    map[Order.Run] = 2;
    map[Order.End] = 3;

    if (map[a] < map[b]) {
        return -1;
    }

    if (map[a] > map[b]) {
        return 1;
    }

    return 0;
}

const data = [Order.End, Order.Run, Order.Start];

const result = data.sort(predicate);

console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM