如何编写基于指定键对任何对象数组进行排序的函数



我正在编写一个排序函数,该函数将数组和键作为参数,并按参数中指定的键返回数组中对象的排序数组

到目前为止,我已经尝试使用排序的比较函数来按字母顺序排列对象 - 但是当我尝试编写一个函数来接受任何对象数组并按任何键对它们进行排序时,它会变得棘手

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 }
]

但相反,它表示键未定义

试试这个:

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 = a[key].toUpperCase();
        let key2 = b[key].toUpperCase();
        if (key1 < key2){
            return -1;
        } else if (key1 > key2){
            return 1;
        }
        return 0;
    });
    return array
}
console.log(sortArrayOfObjects(solarSystem, "name"));

编写自定义排序回调函数进行排序。参考

var 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}
];
solarSystem.sort(function(a, b) {
   return a.name > b.name ? 1 : -1;
});
    
console.log(solarSystem)

或者,借助 ES6 箭头功能:

let 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}
];
solarSystem.sort((a, b) => (a.name > b.name) ? 1 : -1)
console.log(solarSystem)

最新更新