简体   繁体   中英

how to group and sort an array of objects

I got an array of object

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"
}]

I want to sort the array by first using Location.lable then using Name (Ascending order)

Here is what I have already done and it doesn't work

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"))

the result should be like this :

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"
}]

how to sort the array object first using Location.label and then with Name. i tried lodash _.groupBy and after that sort but it didn't work

First, you should use JSON or the JavaScript object in your question.

Then, you can create a sort function that first sorts the label of the user's location, followed by the name of the user.

 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM