javascript - 在javascript中使用多个字段排序?
问题描述
下面我有我的数据,我确实根据状态进行了排序,现在它是这样的
state: ""
state: "CA"
state: "NY"
state: "TX"
state: "xz
但我想检查区域字段,34:"voterid"
如果我们在任何应该首先出现的对象中找到这个(34:"voterid"
),则需要检查这个(),剩下的应该是原样
我期待这样
state: "xz"
state: ""
state: "CA"
state: "NY"
state: "TX"
这是我的代码
var homes = [
{
"h_id":"3",
"city":"Dallas",
"state":"TX",
"zip":"75201",
"price":"162500",
"data":{
"d_id":"3",
"varient":{
"sd":"ss",
"area":{
4:"WARDCODE",
5:"WARDData"
}
}
}
},
{
"h_id":"4",
"city":"Bevery Hills",
"state":"CA",
"zip":"90210",
"price":"319250",
"data":{
"d_id":"3",
"varient":{
"sd":"ss",
"area":{
2:"areacode",
3:"villagecode"
}
}
}
},
{
"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500",
"data":{
"d_id":"3",
"varient":{
"sd":"ss",
"area":{
}
}
}
},
{
"h_id":"6",
"city":"xyz",
"state":"",
"zip":"000103",
"price":"9622300",
"data":{
"d_id":"4",
"varient":{
"sd":"ss",
"area":{
}
}
}
},
{
"h_id":"7",
"city":"wer",
"state":"xz",
"zip":"003103",
"price":"5622300",
"data":{
"d_id":"5",
"varient":{
"sd":"ss",
"area":{
34:"voterid",
56:"votercode"
}
}
}
}
];
sortData('state');
function sortData(param) {
var finaldata = function compare(a, b) {
var A = (a[param]) ? a[param] : "";
var B = (b[param]) ? b[param] : "";
if (A < B)
return -1;
if (A > B)
return 1;
return 0;
};
homes.sort(finaldata);
}
console.log(homes)
解决方案
您可以检查具有所需值的键是否存在,并使用布尔检查的增量将这个所需值排序到顶部。
我用默认值简化了比较部分。
var homes = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500", data: { d_id: "3", varient: { sd: "ss", area: { "4": "WARDCODE", "5": "WARDData" } } } }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250", data: { d_id: "3", varient: { sd: "ss", area: { "2": "areacode", "3": "villagecode" } } } }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500", data: { d_id: "3", varient: { sd: "ss", area: {} } } }, { h_id: "6", city: "xyz", state: "", zip: "000103", price: "9622300", data: { d_id: "4", varient: { sd: "ss", area: {} } } }, { h_id: "7", city: "wer", state: "xz", zip: "003103", price: "5622300", data: { d_id: "5", varient: { sd: "ss", area: { "34": "voterid", "56": "votercode" } } } }];
function sortData(param) {
function compare(a, b) {
return (b.data.varient.area[34] === 'voterid') - (a.data.varient.area[34] === 'voterid')
|| (a[param] || '').localeCompare(b[param] || '');
}
homes.sort(compare);
}
sortData('state');
console.log(homes.map(({ state }) => state)); // just to show states
推荐阅读
- sql - SQL变量到不同的列
- css - 如何为使用ngFor(Angular)动态生成的多个类定义相同的css属性?
- angular - Ionic 4 自定义环境文件
- go - 执行 aws-lambda 函数时出现错误“fork/exec /var/task/main:没有这样的文件或目录”
- javascript - 如何在 vuex 中修改指定的本地存储项?
- ios - Xcode11 存档失败:没有这样的文件或目录 Objects-normal/arm64/UniversalSDK.SwiftFileList
- image - Imagemagick 调整图像大小并减小文件大小
- string - 如何在不重命名文件的情况下从文本文件的行中删除字符?
- gekko - 我应该在哪里找到 python 代码中的设定点变化;在求解 MPC(m.solve(disp=True)) 之后还是之前?
- hadoop - 为什么 YARN 资源管理器失败了?