1

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.

2
  • Please add the code you've attempted to your question as a minimal reproducible example. Commented May 18, 2022 at 19:16
  • store the scores object in a variable and data.sort((a,b) => scores[a.data.id]-scores[b.data.id]); for descending where data is the array u need to sort. switch a and b for ascending Commented May 18, 2022 at 19:25

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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);

1 Comment

OP is not using Typescript, there are no enums.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.