Given an array;
const myArray = [
{
name : "Tom",
age : 28,
eyes : "brown"
},
{
name : "Dave",
age : 45,
eyes : "green"
},
{
name : "Harry",
age : 22,
eyes : "green"
},
];
I know of the simple way to sort an array with the ternary operator
.sort((a, b) => a.age < b.age ? 1 : -1)
but I'm looking to make that age a variable key that I toggle with React useState so it would be more like;
.sort((a, b) => a.toggle < b.toggle ? 1 : -1);
const [toggle, setToggle] = useState('name');
But obviously putting the string 'name' in there won't work and just having name without quote marks returns that the variable does not exist. I've been racking my brain with how to say to JavaScript "use the JSON key, name, or age", not the string or a variable called name/age. Any help on this greatly appreciated!