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