Skip to content
Advertisement

How do i achieve this kind of sorting with JavaScript?

So i have a ‘structure’ like below & i need to sort it with the order of the ‘key values’ below for getting the “output” below. how can i achieve this?

STRUCTURE:

[
    {
        rs: {
            1 MONTHS: "100",
            1 YEAR: "200",
            3 MONTHS: "30",
            6 MONTHS: "400"}

    },
    {
        rs: {
            1 MONTHS: "500",
            1 YEAR: "40",
            3 MONTHS: "700",
            6 MONTHS: "800"}

    },
    {
        rs: {
            1 MONTHS: "199",
            1 YEAR: "1989",
            3 MONTHS: "597",
            6 MONTHS: "20"}

    },
    {
        rs: {
            1 MONTHS: "356",
            1 YEAR: "10",
            3 MONTHS: "877",
            6 MONTHS: "1145"}

    }
]

KEY VALUES:

["10", "20", "30", "40"]

OUTPUT AFTER SORTING

[
    {
        rs: {
            1 MONTHS: "356",
            1 YEAR: "10",
            3 MONTHS: "877",
            6 MONTHS: "1145"}

    },
    {
        rs: {
            1 MONTHS: "199",
            1 YEAR: "1989",
            3 MONTHS: "597",
            6 MONTHS: "20"}

    },
    {
        rs: {
            1 MONTHS: "100",
            1 YEAR: "200",
            3 MONTHS: "30",
            6 MONTHS: "400"}

    },
    {
        rs: {
            1 MONTHS: "500",
            1 YEAR: "40",
            3 MONTHS: "700",
            6 MONTHS: "800"}

    }
]

I want to filter the data structure format i am receiving from an API endpoint to sort it according to the values so that it is in the same order as the key array generated.

Advertisement

Answer

You could take an object for the wanted order and get the value of the object which match for sorting.

const
    getValue = o => Object.values(o).find(v => values.includes(v)),
    data = [{ rs: { "1 MONTHS": "100", "1 YEAR": "200", "3 MONTHS": "30", "6 MONTHS": "400" } }, { rs: { "1 MONTHS": "500", "1 YEAR": "40", "3 MONTHS": "700", "6 MONTHS": "800" } }, { rs: { "1 MONTHS": "199", "1 YEAR": "1989", "3 MONTHS": "597",  "6 MONTHS": "20" } }, { rs: { "1 MONTHS": "356", "1 YEAR": "10", "3 MONTHS": "877", "6 MONTHS": "1145" } }],
    values = ["10", "20", "30", "40"],
    order = Object.fromEntries(values.map((v, i) => [v, i + 1]));

data.sort(({ rs: a }, { rs: b }) => order[getValue(a)] - order[getValue(b)]);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Advertisement