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

时间:2020-02-28 16:44:03

标签: javascript reactjs

我有一个对象数组

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 经过这种排序,但没有成功

1 个答案:

答案 0 :(得分:2)

首先,您应该在问题中使用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; }