javascript - 对数字和文本的多维对象数组进行排序
问题描述
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)
我如何应用必要的修改?谢谢你的时间。
解决方案
您可以采用适用于数字和字符的排序方法,并在路径和排序顺序上使用闭包。
这种方法通过将数组作为第一个参数来使用更改的参数顺序。
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; }
推荐阅读
- r - 在R中查找每日数据与每月平均值的百分比差异
- mongodb - 如何使用 dockerfile 在 centos docker 容器中安装 mongo-org-tools?
- javascript - 如何修复 Heroku 中的 window.open()?
- xml - XSLT:从 XML 文件中提取元素集并从 txt 文件中获取值
- java - Java Parallel Stream 与 ExecutorService 的性能
- c++ - STM32F767ZIT6 Nucleo openocd 闪存
- tensorflow - TF-Lite:将 pb 模型转换为 tflite 后 PReLU 工作不正确
- javascript - 在遵循流规则的同时通过匹配键合并两个对象
- javascript - 自定义变体选择脚本冲突
- python - 当前 win-64 频道中缺少依赖项