I have an array that looks like this:
order = [ "foo", "bar", "baz" ];
This array contains the attribute values I would like to sort my array of objects by. I want to sort the data so that all the objects with name "foo" are first, then "bar", then "baz". My array of objects looks something like this:
data = [
{name: "foo", score: 8},
{name: "baz", score: 4},
{name: "baz", score: 9},
{name: "foo", score: 6},
{name: "bar", score: 9}
];
I want to outcome of the data order to look like this, the array is ordered by name but also by score desc when the names are the same:
sortedData = [
{name: "foo", score: 8},
{name: "foo", score: 6},
{name: "bar", score: 9},
{name: "baz", score: 9},
{name: "baz", score: 4}
];
Here is the code I have tried so far:
order.forEach(name => {
sortedData = [...this.data].sort(function(obj1, obj2) {
return (
-(obj1.name) || obj2.score < obj1.score
);
});
});
console.log(sortedData);