首页 > 解决方案 > 对数字和文本的多维对象数组进行排序

问题描述

var customers = [
  {'Name' : 'John', 'Attributes' : {'Age' : 5, 'Height' : 1.5, 'Country': 'USA', 'Clothes' : {'Shirts' : 5, 'Pants' : 8}}}, 
  {'Name' : 'Andrew', 'Attributes' : {'Age' : 9, 'Height' : 1.8, 'Country': 'Canada', 'Clothes' : {'Shirts' : 2, 'Pants' : 5}}}, 
  {'Name' : 'Lucifer', 'Attributes' : {'Age' : 11, 'Height' : 1.3, 'Country': 'France', 'Clothes' : {'Shirts' : 9, 'Pants' : 4}}}
];

function sort(valuePath, array){
  let path = valuePath.split('.')  

  return array.sort((a, b) => {
     return getValue(b,path) -  getValue(a,path)    
  });

  function getValue(obj, path){
    path.forEach(path => obj = obj[path])
    return obj;
  }
}

如果我触发,我有这个功能的工作结构:

sort('Attributes.Height', customers)

但是,如果我选择使用文本,它就不起作用,例如:

sort('Attributes.Country', customers)

我如何应用必要的修改?谢谢你的时间。

标签: javascriptjqueryarraysobjectmultidimensional-array

解决方案


您可以采用适用于数字和字符的排序方法,并在路径和排序顺序上使用闭包。

这种方法通过将数组作为第一个参数来使用更改的参数顺序。

const
    sort = (array, valuePath, order = 'ASC') => {
        const
            getValue =
                (path => object => path.reduce((o, k) => o[k], object))
                (valuePath.split('.')),
            asc = order === 'ASC' || -1;

        return array.sort((a, b) => {
            const
                aa = getValue(a),
                bb = getValue(b);

            return asc * ((aa > bb) || -(aa < bb));
        });
    };

var customers = [{ Name: "John", Attributes: { Age: 5, Height: 1.5, Country: "USA", Clothes: { Shirts: 5, Pants: 8 } } }, { Name: "Andrew", Attributes: { Age: 9, Height: 1.8, Country: "Canada", Clothes: { Shirts: 2, Pants: 5 } } }, { Name: "Lucifer", Attributes: { Age: 11, Height: 1.3, Country: "France", Clothes: { Shirts: 9, Pants: 4 } } }];


console.log(sort(customers, 'Attributes.Height', 'DESC'));
console.log(sort(customers, 'Attributes.Country', 'DESC'));
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读