gpt4 book ai didi

javascript - 如何对对象数组进行分组和排序

转载 作者:行者123 更新时间:2023-12-04 10:30:06 24 4
gpt4 key购买 nike

我得到了一个对象数组

const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},

{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]

我想先使用 Location.lable 然后使用 Name(升序)对数组进行排序

这是我已经完成的工作,但它不起作用
const dynamicSort = property => {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function(a, b) {
var result;
if (property === "deviceLocation")
result =
a[property].label < b[property].label
? -1
: a[property].label > b[property].label
? 1
: 0;
else
result =
a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0;
return result * sortOrder;
};
};
users.sort(dynamicSort("deviceLocation"))

结果应该是这样的:
const users= [{
Location: {
label: "aa",
value: "aa"
},
Name: "test4"
id: "003"
},

Location: {
label: "aa",
value: "aa"
},
Name: "test7"
id: "002"
},

{
Location: {
label: "ss",
value: "ss"
},
Name: "test4"
id: "004"
}]

如何首先使用 Location.label 然后使用 Name 对数组对象进行排序。我试过 lodash _.groupBy
在那之后,但它没有用

最佳答案

首先,您应该在问题中使用 JSON 或 JavaScript 对象。

然后,您可以创建一个排序函数,该函数首先对用户所在位置的标签进行排序,然后是用户的姓名。

console.log(getUsers().sort(userComparator));

function userComparator(userA, userB) {
let diff = userA.Location.label.localeCompare(userB.Location.label);
return diff === 0 ? userA.Name.localeCompare(userB.Name) : diff;
}

function getUsers() {
return [{
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test7",
"id": "002"
}, {
"Location": {
"label": "jaffna",
"value": "jaffna"
},
"Name": "test4",
"id": "004"
}, {
"Location": {
"label": "colombo",
"value": "colombo"
},
"Name": "test4",
"id": "003"
}];
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

关于javascript - 如何对对象数组进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60455989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com