I have an array of movies that I am trying to sort based on a dynamic value labeled 'path' which evaluates to either 'title', 'genre.name', 'numberInStock', or 'dailyRentalRate' depending on the current state. However, because the 'genre' property within the movies array is an object and not a string like the others, the compare function I wrote tries to access movieA("genre.name") and movieB("genre.name"). I thought this syntax might work but it does not. Surely there must an elegant way to write my compare function that does not require just adding more conditionals for when path is set to 'genre.name"? Any help or insight is greatly appreciated. Thanks. (Below is some code snippets)
var movies = [
{
title: "Terminator",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 6,
dailyRentalRate: 2.5,
},
{
title: "Die Hard",
genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
numberInStock: 5,
dailyRentalRate: 2.5
},
{
title: "Get Out",
genre: { _id: "5b21ca3eeb7f6fbccd471820", name: "Thriller" },
numberInStock: 8,
dailyRentalRate: 3.5
}
]
this.state = {
path: "title" //'title' or 'genre.name' or 'numberInStock' or 'dailyRentalRate'
};
myCompare = (a, b) => {
const path = this.state.path;
if (a[path] < b[path]) return - 1;
if (a[path] > b[path]) return 1;
return 0;
}
const moviesSorted = movies.sort(this.myCompare);