在JavaScript中按字母顺序对数组及其对象键进行排序 [英] Sort array and its object key in alphabetical order in javascript
问题描述
我有一个以下格式的数组.我已经按字母顺序对数组进行了排序,但是数组中的每个元素都存在一个子数组.我也想按字母顺序对它们进行排序.
I have an array in the following format. I have sorted the array in alphabetical order.But every element in the array, a sub array exist. I would like to sort them in alphabetical order too.
var myObj = [
{
"name":"John",
"items": [
{ "id":1, "car":"maruti" },
{ "id":2, "car":"wolks" },
{ "id":3, "car":"bmw" }
]},
{
"name":"Peter",
"items": [
{ "id":4, "car":"alto" },
{ "id":5, "car":"swift" },
]
}
];
这是我用来对主数组进行排序的代码.在这里,我想按字母顺序对项"数组进行排序.
This is the code I have used to sort the main array. Here I would like to sort the 'items' array in alphabetical order.
myObj.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
if (nameA < nameB) {
return -1
}
if (nameA > nameB){
return 1
}
return 0
});
推荐答案
在sort
函数 other 中除了对数组中的直接项目进行排序以外,感觉不正确-我重复两次,一次对myObj
进行排序,一次对每个items
属性进行排序.
It doesn't feel right to do anything in a sort
function other than sort the immediate items in the array - I'd iterate twice, once to sort the myObj
, and once to sort each items
property.
您还可以使用localeCompare
来简化代码:
You can also use localeCompare
to simplify your code:
var myObj=[{"name":"John","items":[{"id":1,"car":"maruti"},{"id":2,"car":"wolks"},{"id":3,"car":"bmw"}]},{"name":"Peter","items":[{"id":4,"car":"alto"},{"id":5,"car":"swift"},]}]
myObj.sort((a, b) => a.name.localeCompare(b.name));
myObj.forEach(({ items }) => items.sort((a, b) => a.car.localeCompare(b.car)));
console.log(myObj);
这篇关于在JavaScript中按字母顺序对数组及其对象键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!