简体   繁体   中英

How can I sort a array of objects by a parameter inside an objects?

For example, I have a array of objects returned by back-end, with positions as string.

[
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]

I need reorganize this array, by key "position", but I need mantein all objects, including nulls in yours original positions (nulls must be after those with position).

[
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "pink",
        "position": "THIRD"
    },
    {
        "color": "blue",
        "position": null
    },
]

I tryed use a map with possible positions with slice, but my array stays out of order.

Is there a way to have different values in the "position" field?

You could try something like this:

let test = [
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]


test.sort((a,b) => a.position > b.position ? 1 : -1)  //for ascending order

test.sort((a,b) => a.position > b.position ? -1 : 1)  //for descending order

But it's just a coincidence that "first", "second" and "third" are in alphabetical order

const input = [ { color: "red", position: "SECOND", }, { color: "blue", position: null, }, { color: "green", position: "FIRST", }, { color: "pink", position: "THIRD", }, { color: "yellow", position: "FOURTH", }, ]; const sortOrder = [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", ]; function doCustomSort(a, b, customSortOrder) { if (a.position === null && b.position !== null) { return 1; } else if (a.position !== null && b.position === null) { return -1; } return ( sortOrder.indexOf(a.position.toLowerCase()) - sortOrder.indexOf(b.position.toLowerCase()) ); } console.log(input.sort((a, b) => doCustomSort(a, b, sortOrder)));

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