I'm writing a sort function that takes array and key as parameters and returns the sorted array of objects within the array by the key specified in the parameter
So far, I've tried to use the compare function using sort to alphabetize an object -- however it gets tricky when I try to write a function that takes any array of objects and sorts them by any key
solarSystem =[
{name: "Mercury", position: 1},
{name: "Venus", position: 2},
{name: "Earth", position: 3},
{name: "Mars", position: 4},
{name: "Jupiter", position: 5},
{name: "Saturn", position: 6},
{name: "Uranus", position: 7},
{name: "Neptune", position: 8},
{name: "Pluto", position: 9}
];
sortArrayOfObjects = (array, key) => {
array.sort(function (a, b){
let key1 = array.key.toUpperCase();
let key2 = array.key.toUpperCase();
if (key1 < key2){
return -1;
} else if (key1 > key2){
return 1;
}
return 0;
});
}
console.log(sortArrayOfObjects(solarSystem, "name"));
I expect the output to be:
[
{ name: 'Earth', position: 3 },
{ name: 'Jupiter', position: 5 },
{ name: 'Mars', position: 4 },
{ name: 'Mercury', position: 1 },
{ name: 'Neptune', position: 8 },
{ name: 'Pluto', position: 9 },
{ name: 'Saturn', position: 6 },
{ name: 'Uranus', position: 7 },
{ name: 'Venus', position: 2 }
]
but instead it indicates that key is undefined