-1

I have an array that is grouped based on the EmployeeId. Now, I need to sort it based on EmployeeName in ascending order. Below is the array

 13: [{employeeId:13,employeeName:"Nova"}]
 21: [{employeeId:21,employeeName:"Avinash"},{employeeId:21,employeeName:"Avinash"} ]
 23: [{employeeId:23,employeeName:"Mamatha"}]
 24: [{employeeId:24,employeeName:"Swetha"}]
}

Sort the array based on employeeName and return the list same as the input The output should be as follows:

{
 21: [{employeeId:21,employeeName:"Avinash"},{employeeId:21,employeeName:"Avinash"} ]
 23: [{employeeId:23,employeeName:"Mamatha"}]
 13: [{employeeId:13,employeeName:"Nova"}]
 24: [{employeeId:24,employeeName:"Swetha"}]
}
P.S
  • 3
  • 2
sra
  • 1
  • 1
  • Hello @sra, welcome to stackoverflow. I guess your question is not related to Vue js, as it is a javascript question. You can use the [`sort` function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) on arrays to sort the items of the list. You might want to check this question: https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value – Leif Marcus Jan 03 '23 at 10:56
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Leif Marcus Jan 03 '23 at 10:57
  • If I do the same I am not getting the ouput correctly. I am getting the tasks individually – sra Jan 03 '23 at 11:53

1 Answers1

0

Imagine your list looks as follows in JavaScript

const list = [
  [{ employeeId: 13, employeeName: "Nova" }],
  [{ employeeId: 21, employeeName: "Avinash" }, { employeeId: 21, employeeName: "Avinash" }],
  [{ employeeId: 23, employeeName: "Mamatha" }],
  [{ employeeId: 24, employeeName: "Swetha" }],
]

you can sort it like

list.sort(([a], [b]) => a.employeeName.localeCompare(b.employeeName))

which is the short version of

list.sort((a, b) => {
  const itemA = a[0];
  const itemB = b[0];
  return itemA.employeeName.localeCompare(itemB.employeeName);
})

Please note: that the sort function will mutate your initial list. To avoid that you can do

const sorted = [...list].sort(([a], [b]) => a.employeeName.localeCompare(b.employeeName))

Update

Just a side note: In javascript object keys cannot be ordered. you might want to look into the following answer: https://stackoverflow.com/a/5525820/9154829

Leif Marcus
  • 478
  • 4
  • 6